1 <?php 2 /* 3 instanceof is used to determine whether a PHP variable is an instantiated object of a certain class: 4 */ 5 class MyClass 6 { 7 8 } 9 10 class NotMyClass 11 { 12 13 } 14 15 $a = new MyClass; 16 17 var_dump($a instanceof MyClass); 18 var_dump($a instanceof NotMyClass); 19 // boolean true boolean false 20 /* 21 instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class: 22 */ 23 24 class ParentClass 25 { 26 27 } 28 29 class ChildClass extends ParentClass 30 { 31 32 } 33 34 $a = new ChildClass; 35 var_dump($a instanceof ChildClass); 36 var_dump($a instanceof ParentClass); 37 // true true 38 /* 39 Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface: 40 */ 41 42 interface MyInterface 43 { 44 45 } 46 47 class MyClass2 implements MyInterface 48 { 49 50 } 51 52 $a = new MyClass2; 53 54 var_dump($a instanceof MyClass2 ); 55 var_dump($a instanceof MyInterface); 56 // true true 57 58 /* 59 Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable: 60 */ 61 62 $b = new MyClass2; 63 $c = ‘MyClass2‘; 64 $d = ‘NotMyClass2‘; 65 66 var_dump($a instanceof $b); //$b is an object of class MyClass 67 var_dump($a instanceof $c); //$c is a string ‘MyClass‘ 68 var_dump($a instanceof $d); //$d is a string ‘NotMyClass‘ 69 70 //true true false 71 72 $e = ‘MyClass2‘; 73 var_dump($e instanceof $c); 74 var_dump($c instanceof $e); 75 76 //false false 77 78 /* 79 instanceof does not throw any error if the variable being tested is not an object, it simply returns FALSE. Constants, however, are not allowed. 80 */ 81 $a = 1; 82 $b = null; 83 $c = imagecreate(5,5); 84 var_dump($a instanceof stdClass); 85 var_dump($b instanceof stdClass); 86 var_dump($c instanceof stdClass); 87 // false false false 88 /* 89 var_dump(false instanceof stdClass); 90 Fatal error: instanceof expects an object instance, constant given 91 */
发问:
0-
<?php $c = ‘MyClass2‘; $e = ‘MyClass2‘; var_dump($c instanceof $e); //boolean false ???Fatal error
原文:http://www.cnblogs.com/yuanjiangw/p/5782492.html