& Lt ;? PhpclassMyClass {} classNotMyClass {} $ anewMyClass; var_dump ($ ainstanceofMyClass); var_dump ($ ainstanceofNotMyClass );? & Gt; instanceof is used to determine whether a PHP variable belongs to a class:
Example #1 use instanceof for a pair of classes
The above routine will output:
Bool (true)
Bool (false)
Instanceof can also be used to determine whether a variable inherits from an instance of a subclass of a parent class:
Example #2 use instanceof for the inheritance class
The above routine will output:
Bool (true)
Bool (true)
Check whether an object is not an instance of a class. you can use the logical operator not.
Example #3 use instanceof to check instances where the object is not a class
The above routine will output:
Bool (true)
Finally, instanceof can also be used to determine whether a variable is an instance of an object that implements an interface:
Example #4 use instanceof
The above routine will output:
Bool (true)
Bool (true)
Although instanceof is usually used directly with the class name, you can also use an object or string variable:
The above routine will output:
Bool (true)
Bool (true)
Bool (false)
If the detected variable is not an object, instanceof returns FALSE instead of sending any error message. Constants cannot be detected.
Example #6 use instanceof to detect other variables
The above routine will output:
Bool (false)
Bool (false)
Bool (false)
PHP Fatal error: instanceof expects an object instance, constant given
However, the use of instanceof has some traps that must be understood. Before PHP 5.1.0, if the class name to be checked does not exist, instanceof will call _ autoload (). In addition, a fatal error occurs if the class is not loaded. You can avoid this problem by using dynamic class references or using a string variable containing the class name:
Example #7 avoid class name searches and fatal errors caused by instanceof in PHP 5.0
The above routine will output:
Bool (false)
The instanceof operator is introduced in PHP 5. Is_a () was used before, but is_a () was discarded and replaced with instanceof. Note that is_a () has been used again since PHP 5.3.0.