pTutorial

New way to learn PHP

PHP 5 instanceof operator

instanceof operator

PHP5 introduced new operator named instanceof operator, the functionality of PHP5 instanceof operator is same as PHP 4 is_a() method (which is now deprecated).

instanceof operator is used to check whether both object passed as operands point the same class. It returns true if both objects belong to the same object otherwise return false.

Example of instanceof operator

<?php
Class Computer
{
	public $name = "HCL";
} 

$obj1 = new Computer();
$obj2 = new Computer();
if($obj1 instanceof $obj2)
{
echo "Both object represent same class
"; echo "Name: ".$obj1->name; } else { echo "Both object does not represent same class
"; echo "Name: ".$obj1->name; } ?>

Output

Both object represent same class
Name: HCL

In the above example, first of all create two objects that belong to the Computer class named $obj1 and $obj2. Both of object belong to the same object so the result will be "Both objects represent the same class" and "HCL".

Note: In the above case you can replace the first object to the second and second to the first.

Compare with class name

You can also use intanceof operator to compare an object with the name of the class, as shown below.

Example of instanceof operator

<?php
Class Computer
{
	public $name = "HCL";
} 
$obj1 = new Computer();
$obj2 = new Computer();
if($obj1 instanceof Computer)
{
echo "Both object represent same class
"; echo "Name: ".$obj1->name; } else { echo "Both object does not represent same clsaa
"; echo "Name: ".$obj1->name; }?>

Output

Both object represent same class
Name: HCL

Note: In case of a class name, class name must be right hand side.

instanceOf operator in inheritance

include 'Computer.php';
Class SuperComputer extends Computer
{
	public $name = "HCL";
} 
$obj1 = new SuperComputer();
$obj2 = new Computer();
if($obj2 instanceof $obj1)
{
echo "Both object represent same class
"; echo "First class :".get_class($obj1); echo "
Second class :".get_class($obj2); } else { echo "Both object does not represent same class
"; echo "First class :".get_class($obj1); echo "
Second class :".get_class($obj2); }

Output

Both object does not represent same class
First class :SuperComputer
Second class :Computer

Note: In the case of the inheritance parent class object must be left hand side.


QUOTES OF THE DAY

We are never deceived we deceive ourselves.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER