instanceof Operator


instanceof Operator


The instanceof operator is used in PHP to find out if an object is an instantiated instance of a class. It's quite easy to use and works in the same sort of way as other operators.


<?php class Person { }

$p1 = new Person();

if($p1 instanceof Person)

   echo "True";

else

   echo "False";

?>

Output:true


<?php

class Person1 {}

class Person2 extends Person1{}

$p3 = new Person1();

$p2=new Person2();

$p4 = new Person1();

if($p3 instanceof $p2)

   echo "True";

else

   echo "False";?>

Output: False


In the above example, on line number $p1 object is being compared to check if its a Person type of object. In this case $p1 is a Person type of object and hence the output is True. Otherwise it’s a false.

Custom Search

%d bloggers like this: