Object type information

The keywords instanceof and is_subclass_of are used to return a boolean TRUE or FALSE value when an object is evaluated against a class name.

 

instanceof will return TRUE if the object belongs to the specified class, or a descendant of that class.

 

Syntax:

$myObject instanceof MyClass;

 

This example creates two objects and tests whether they are instances of the Parent or Child class:

Save & refresh browser:

The r1 object belongs to the Bike class
The m1 object belongs to the Bike class
The r1 is not a MotoGP class object
The m1 object belongs to the MotoGP class

 

It can be seen that the m1 is a Bike object, since it is inherited from the Bike class. Similarly, it can be seen that the r1 object is not a MotoGP object.

 

To determine is an object is just from a child class is_subclass_of will return TRUE if the object is a descendant of the specified class.

 

Syntax:

is_sub_class($myObject, MyClass);

 

This example creates two objects and tests whether they are in sub classes of the the Parent or Child class:

Save & refresh browser:

The r1 object is NOT in a sub class of the Bike class
The m1 object IS in a sub class of the Bike class
The r1 object is NOT in a sub class of the MotoGP class
The m1 object is NOT in a sub class of the MotoGP class

 

As expected only the m1 object is in a sub class

Leave a Reply