instanceof的用法

(1)判断一个对象是否是某个类的实例。

(2)判断一个对象是否实现了某个接口。

1 <?php
2 $obj = new A();
3 if ($obj instanceof A) {
4    echo 'A';
5 }
<?php
interface ExampleInterface
{
     public function interfaceMethod();
 }
 
 class ExampleClass implements ExampleInterface
{
     public function interfaceMethod()
     {
         return 'Hello World!';
     }
 }
 
$exampleInstance = new ExampleClass();
 
 if($exampleInstance instanceof ExampleInterface){
     echo 'Yes, it is';
 }else{
     echo 'No, it is not';
} 
?>
 
输出结果:Yes, it is

猜你喜欢

转载自www.cnblogs.com/xiaohuiji/p/9042419.html
今日推荐