判断该变量是否属于某一类的实例

  1. <?php
  2. class MyClass
  3. {
  4. }
  5. class NotMyClass
  6. {
  7. }
  8. $a = new MyClass;
  9. var_dump($a instanceof MyClass); // true
  10. var_dump($a instanceof NotMyClass); // false
  11. ?>

判断变量是否集成某一父类的子类

  1. <?php
  2. class ParentClass
  3. {
  4. }
  5. class MyClass extends ParentClass
  6. {
  7. }
  8. $a = new MyClass;
  9. var_dump($a instanceof MyClass); // true
  10. var_dump($a instanceof ParentClass); // true
  11. ?>

也可以判断接口

  1. <?php
  2. interface MyInterface
  3. {
  4. }
  5. class MyClass implements MyInterface
  6. {
  7. }
  8. $a = new MyClass;
  9. var_dump($a instanceof MyClass); // true
  10. var_dump($a instanceof MyInterface); // true
  11. ?>

还可以对变量进行使用

  1. <?php
  2. interface MyInterface
  3. {
  4. }
  5. class MyClass implements MyInterface
  6. {
  7. }
  8. $a = new MyClass;
  9. $b = new MyClass;
  10. $c = 'MyClass';
  11. $d = 'NotMyClass';
  12. // $b is an object of class MyClass
  13. var_dump($a instanceof $b); //true
  14. // $c is a string 'MyClass'
  15. var_dump($a instanceof $c); //true
  16. // $d is a string 'NotMyClass'
  17. var_dump($a instanceof $d); //false
  18. ?>