How to compare two objects in PHP

When we talked about operators I mentioned we have the == operator to check if two values are equal and === to check if they are identical.

Mainly the difference is that == checks the object content, for example the '5' string is equal to the number 5, but it’s not identical to it.

When we use those operators to compare objects, == will check if the two objects have the same class and have the same values assigned to them.

=== on the other hand will check if they also refer to the same instance (object).

For example:

class Dog {
  public $name = 'Good dog';

$roger = new Dog();
$syd = new Dog();

echo $roger == $syd; //true

echo $roger === $syd; //false

Download my free PHP Handbook!