Comparing Objects
When comparing objects, the == and === operators function differently:
Using the == Operator:
- The
==
operator (equality) checks if two objects have the same attributes and values. It doesn't consider whether they are the same instance or not. - If two objects are instances of the same class and have the same attribute values, then
$object1 == $object2
will returntrue
.
Using the === Operator:
- The
===
operator (identity) checks if two objects are referencing the exact same instance in memory. - It returns
true
only if both variables being compared point to the same object instance.
Comparing with the == Operator
Let's look at a simple example of using the ==
operator. Imagine we had a class called Sample
.
class Sample {
public $value;
public function __construct($value) {
$this->value = $value;
}
}
Next, we can create instances of this class and then compare them like so:
$a = new Sample(5);
$b = new Sample(5);
$c = $a;
var_dump($a == $b); // bool(true) because both have the same property values
In the example, $a
and $b
are two different instances with the same value, so they are equal (==
). $a
and $c
are the same instance, so they are both equal (==).
Comparing with the === Operator
But what if we used the ===
operator instead?
var_dump($a === $b); // bool(false) because they are different instances
var_dump($a === $c); // bool(true) because both reference the same instance
In the example, $a
and $b
are not identical (===
). On the other hand, $a
and $c
are the same instance, so they are identical (===
).
Criteria (Comparison Basis) | == | === |
---|---|---|
Both objects point to identical instance | true | true |
Objects have identical property values | true | false |
Objects have differing property values | false | false |
Key Takeaways
- Objects can be compared using the
==
(equality) and===
(identity) operators. - Equality
(==)
compares objects based on their attributes and their respective values. - Identity
(===)
compares whether two objects are the exact same instance in memory. - For two objects referencing the same instance:
==
and===
both returntrue
. - For different instances with identical attribute values:
==
returnstrue
, but===
returnsfalse
. - For objects with differing attribute values: Both
==
and===
returnfalse
. - Understanding the distinction between these operators is crucial when working with objects to avoid unintended behaviors, especially in conditions and logic evaluations.