Home > Article > Backend Development > php type operator
instanceof is used to determine whether a PHP variable belongs to an instance of a certain class:
Example #1 Using instanceof
on a class The above routine will output:
bool(true)
bool(false)
instanceof also Can be used to determine whether a variable is an instance of a subclass inherited from a certain parent class:
Example #2 Use instanceof
on the inherited class The above routine will output:
bool(true)
bool(true)
To check whether an object is not an instance of a class, you can use the logical operator not.
Example #3 Use instanceof to check that the object is not an instance of a certain class
The above routine will output:
bool(true)
Finally, instanceof can also be used to determine whether a variable is an object that implements a certain interface Example of:
Example #4 Using instanceof
on an interface The above routine will output:
bool(true)
bool(true)
Although instanceof is usually used directly with the class name, it can also use objects or characters String variable:
The above routine will output:
bool(true)
bool(true)
bool(false)
If the variable being detected is not an object, instanceof does not issue any error message but returns FALSE. Not allowed to detect constants.
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 There are some pitfalls when using instanceof that you must be aware of. Prior to PHP 5.1.0, instanceof would call __autoload() if the class name to be checked did not exist. Additionally, a fatal error is generated if the class is not loaded. You can avoid this problem by using a dynamic class reference or a string variable containing the class name:
Example #7 Avoid the class name lookup and fatal error problems caused by instanceof in PHP 5.0
The above routine will output :
bool(false)
instanceof operator was introduced in PHP 5. Before this, is_a() was used, but later is_a() was abandoned and replaced by instanceof. Note that as of PHP 5.3.0, the use of is_a() is restored.