PHP Compare Objects
Summary: in this tutorial, you will learn how to compare objects in PHP using comparison operator ( 
==) and identity operator ( ===).
Let’s create a new class for demonstration.
The 
Point class has two properties:  $x coordinate and  $y coordinate.Comparing objects using comparison operator (==)
When we compare objects using comparison operator ( 
==), two objects are equal if they are the instances of the same class and have the same properties and values.
Let’s add a static method to compare two Point objects:
Now, we create two new objects with the same properties’ values and compare them:
Two Points are equal.
We can assign  
$p2 to a new reference $p3, both  $p2 and  $p3 are pointing the the same object.$p2 and  $p3 are equal as well.
Now we can create a new point object with different properties’ values and compare it with 
$p3:$p3 and  $p4 are not equal.Comparing objects using identity operator (===)
When you use the identity operator to compare objects, they are identical if and only if both of them refer the the same instance of class.
The following  
$p1 and  $p2 objects are identical when we use identity operator ( ===) to compare because they are all refer to the same object.
However the following  
$p3 object is not identical to the  $p1 even their properties values are the equal.| 
1 
2 
3 
4 
5 
6 | 
$p3 = new Point(10,20); 
if($p1 === $p3){ 
 echo 'p1 and p3 are identical'; 
}else{ 
 echo 'p1 and p3 are not identical'; 
} | 
 
No comments:
Post a Comment