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.
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.
$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.
<?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 ";}?>
The code snippet is explained below.
AnewClass
, which extends MyClass
.$an_obj
was created from the derived class AnewClass
.instanceof
keyword in the if
condition. On success, the if
code 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.