PHP5 introduces a new operator. instanceOf is used to check if two objects passed as operands belong to the same class. This check can also happen when an object is compared with a class name.
In PHP4 a similar functionality existed with a method is_a(), it has been replaced by the instanceOf operator in PHP5.
Lets look at an example below:
class Person { ... } $p1 = new Person(); $p2 = new Person(); if($p1 instanceof $p2) echo "True"; else echo "False";
In the above example, we are comparing to check if $p1 and $p2 belong to the same class i.e. Person. In this case $p1 and $p2 both belong to the same class Person and hence the output is True. Please note that line number 8 can also be written as if($p2 instanceof $p1) and will yield the same output.You can also use instanceOf operator to compare an object with the name of the class, look at the example below:
class Person { ... } $p1 = new Person(); if($p1 instanceof Person) echo "True"; else echo "False";
In the above example, on line number 7 $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.Behaviour of instanceOf operator in inheritance
class Customer extends Person { ... } $p1 = new Person(); $c1 = new Customer(); if($c1 instanceof $p1) echo "True"; else echo "False";
In the above example, on line number 8 $c1 child class object is being compared with $p1 which is a parent class object. This is possible because Customer class is a child of the Person Class, just that the Customer class is a specialized form of the Person class and therefore this becomes possible. However the reverse is not possible, we cannot compare if($p1 instanceof $c1) and will result in an error.
No comments:
Post a Comment