Please wait

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 return true.

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 instancetruetrue
Objects have identical property valuestruefalse
Objects have differing property valuesfalsefalse

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 return true.
  • For different instances with identical attribute values: == returns true, but === returns false.
  • For objects with differing attribute values: Both == and === return false.
  • Understanding the distinction between these operators is crucial when working with objects to avoid unintended behaviors, especially in conditions and logic evaluations.

Comments

Please read this before commenting