What is the instanceof keyword in PHP?
Overview
Objects are instances of a class. That is, they are created using classes as their blueprints. When classes are created, they inherit the properties and methods of the class from which they are made. They can also contain custom properties and methods of their own. An object can simply be created as shown below, using the new keyword.
$my_object = new my_ClassName;
Somewhere in your code, you might want to confirm or check if a particular object is an instance of a particular object, and if so, something should happen. If not, another should. This can be achieved using the instanceof keyword in PHP.
What is the instanceof keyword in PHP?
The instanceof keyword will check if an object is created from or simply put to a class.
The return value of this comparison is a boolean, which is true in the event that the object is an instance of the class and false if not.
Basic syntax
$object instanceof class_name;
The instanceof keyword will compare the variable at the left (the object) to that at the right (the class) and return a true or false value.
Code
<?phpclass MyClass {}class AnewClass extends MyClass{}$an_obj = new AnewClass();if($an_obj instanceof AnewClass) {echo "This object is from AnewClass \n";}/* The object is also an instance of theclass it is derived from */if($an_obj instanceof MyClass) {echo "The object is also from MyClass ";}?>
Explanation
The code snippet is explained below.
- On line 2, a class was created.
- Line 3 saw the creation of a new class,
AnewClass, which extendsMyClass. - Then, on line 4, the object
$an_objwas created from the derived classAnewClass. - The object was checked for membership using the
instanceofkeyword in theifcondition. On success, theifcode block will be executed.
From the output of the code, you can see that the object is an instance of both the parent class and the child class from which it was created.