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:

<?php
	class Bike {}
	class MotoGP extends Bike {}

	$r1 = new Bike;
	$m1 = new MotoGP;

	if ($r1 instanceof Bike){
		echo "The r1 object belongs to the Bike class<br>";
	} else {
		echo "The r1 is not a Bike class object<br>";
	}

	if ($m1 instanceof Bike){
		echo "The m1 object belongs to the Bike class<br>";
	} else {
		echo "The m1 is not a Bike class object<br>";
	}

	if ($r1 instanceof MotoGP){
		echo "The r1 object belongs to the BikeMotoGP class<br>";
	} else {
		echo "The r1 is not a MotoGP class object<br>";
	}

	if ($m1 instanceof MotoGP){
		echo "The m1 object belongs to the MotoGP class<br>";
	} else {
		echo "The m1 is not a MotoGP class object<br>";
	}
?>

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:

<?php
	class Bike {}
	class MotoGP extends Bike {}

	$r1 = new Bike;
	$m1 = new MotoGP;

	if (is_subclass_of ($r1, Bike)){
		echo "The r1 object IS in a sub class of the Bike class<br>";
	} else {
		echo "The r1 object is NOT in a sub class of the Bike class<br>";
	}

	if (is_subclass_of ($m1, Bike)){
		echo "The m1 object IS in a sub class of the Bike class<br>";
	} else {
		echo "The m1 object is NOT in a sub class of the Bike class<br>";
	}

	if (is_subclass_of ($r1, MotoGP)){
		echo "The r1 object IS in a sub class of the MotoGP class<br>";
	} else {
		echo "The r1 object is NOT in a sub class of the MotoGP class<br>";
	}

	if (is_subclass_of ($m1, MotoGP)){
		echo "The m1 object IS in a sub class of the MotoGP class<br>";
	} else {
		echo "The m1 object is NOT in a sub class of the MotoGP class<br>";
	}
?>

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