The instanceof Operator
The instanceof
operator checks if an object is an instance of the specified class
or its descendant. It accepts the object as the first parameter and the class name for checking as the second.
Returns true
if the object belongs to the class or false
otherwise.
Syntax
$object instanceof ClassName;
Example
Let's check if the object is an instance of the MyClass
class:
<?php
class MyClass {}
$obj = new MyClass();
var_dump($obj instanceof MyClass);
?>
Code execution result:
true
Example
Let's check class inheritance:
<?php
class ParentClass {}
class ChildClass extends ParentClass {}
$child = new ChildClass();
var_dump($child instanceof ParentClass);
?>
Code execution result:
true
Example
Let's check that the object is not an instance of the class:
<?php
class A {}
class B {}
$a = new A();
var_dump($a instanceof B);
?>
Code execution result:
false