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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?php class Point{ private $x; private $y; public function __construct($x,$y){ $this->x = $x; $this->y = $y; } public function setX($x){ $this->x = $x; } public function getX(){ return $this->x; } public function setY($y){ $this->y = $y; } public function getY(){ return $this->y; } } |
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:
1 2 3 4 5 6 7 8 9 | /** * Compare two points * @param Point $p1 * @param Point $p2 * @return boolean return true if two points are equal, otherwise returns false */ public static function compare($p1,$p2){ return $p1 == $p2; } |
Now, we create two new objects with the same properties’ values and compare them:
1 2 3 4 5 6 7 8 9 | $p1 = new Point(10,20); $p2 = new Point(10,20); if(Point::compare($p1, $p2)){ echo 'p1 and p2 are equal <br/>'; } else{ echo 'p1 and p2 are not equal <br/>'; } |
Two Points are equal.
We can assign $p2
to a new reference $p3
, both $p2
and $p3
are pointing the the same object.
1 2 3 4 5 6 7 | $p3 = $p2; if(Point::compare($p2, $p3)){ echo 'p2 and p3 are equal <br/>'; } else{ echo 'p2 and p3 are not equal <br/>'; } |
$p2
and $p3
are equal as well.
Now we can create a new point object with different properties’ values and compare it with $p3
:
1 2 3 4 5 6 7 | $p4 = new Point(20,10); if(Point::compare($p3, $p4)){ echo 'p3 and p4 are equal <br/>'; } else{ echo 'p3 and p4 are not equal <br/>'; } |
$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.
1 2 3 4 5 6 7 8 9 | <?php $p1 = new Point(10,20); $p2 = $p1; if($p1 === $p2){ echo '$p1 and $p2 are identical'; }else{ echo '$p1 and $p2 are not identical'; } |
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'; } |
You can download the script file of the PHP compare objects tutorial via the following link:
PHP Compare Objects (1247 downloads)In this tutorial, we have shown you to compare object for equality and identity.