作用:
(1)判断一个对象是否是某个类的实例;
(2)判断一个对象是否实现了某个接口。
第一种用法: <?php$obj = new A();
if ($obj instanceof A)
{
echo 'A';
}
第二种用法: <?phpinterface 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
另外,需注意 instanceof 与 is_subclass_of() 的区别,请看代码: <?php class Foo { public $foobar = 'Foo'; public function test() { echo $this->foobar . "\n"; } } class Bar extends Foo { public $foobar = 'Bar'; } $a = new Foo(); $b = new Bar(); echo "use of test() method\n"; $a->test(); $b->test(); echo "instanceof Foo\n"; var_dump($a instanceof Foo); // TRUE var_dump($b instanceof Foo); // TRUE echo "instanceof Bar\n"; var_dump($a instanceof Bar); // FALSE var_dump($b instanceof Bar); // TRUE echo "subclass of Foo\n"; var_dump(is_subclass_of($a, 'Foo')); // FALSE var_dump(is_subclass_of($b, 'Foo')); // TRUE echo "subclass of Bar\n"; var_dump(is_subclass_of($a, 'Bar')); // FALSE var_dump(is_subclass_of($b, 'Bar')); // FALSE ?> 输出结果(PHP 5.4.4): use of test() method Foo Bar instanceof Foo bool(true) bool(true) instanceof Bar bool(false) bool(true) subclass of Foo bool(false) bool(true) subclass of Bar bool(false)