判断该变量是否属于某一类的实例
<?php
class MyClass
{
}
class NotMyClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass); // true
var_dump($a instanceof NotMyClass); // false
?>
判断变量是否集成某一父类的子类
<?php
class ParentClass
{
}
class MyClass extends ParentClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass); // true
var_dump($a instanceof ParentClass); // true
?>
也可以判断接口
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
var_dump($a instanceof MyClass); // true
var_dump($a instanceof MyInterface); // true
?>
还可以对变量进行使用
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';
// $b is an object of class MyClass
var_dump($a instanceof $b); //true
// $c is a string 'MyClass'
var_dump($a instanceof $c); //true
// $d is a string 'NotMyClass'
var_dump($a instanceof $d); //false
?>