Custom Search

OOPS in PHP 5 - instanceOf Operator

PHP5 has come up with a new operator “instanceof”. This operator is used to check whether the objects passed as operands to this method belongs to the same class or not. This is very useful in runtime environment where you want to know the parent of the class. If left operand belongs to the child class and the right to the parent class, then too the result of instanceof is true. But, vice-versa is not true.





Example

< ?
class Person
{
 
}
 
$p1 = new Person();
$p2 = new Person();
 
if($p1 instanceof $p2)
     echo "True";
else
     echo "False";
?>

Output: True
Explanation:
Here i am checking whether the $p1 belongs to $p2 or not. If the condition is true then it will return “True” else it will return “False”.

Example2:

< ?
class Person
{
 
}
 
class Customer extends Person
{
 
}
 
$p1 = new Person();
$c1 = new Customer();
 
if($p1 instanceof $c1)
      echo "True";
else
      echo "False";
?>

Output: This will return True followed by False

Similar Posts

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)