4.9. Comparing Objects

At their simplest, objects are data types. You can compare objects with the equal operator, which is two equal signs (==), or with the identical operator, which is three equal signs (===). Using the equal operator, two objects are equal if they are created from the same class and have the same properties and values. However, using the identical operator, two objects are identical only if they refer to the same instance of the same class.

The following two objects are equal, but not identical, because they are two instances of the class Car:

$my_car = new Car();
$my_car2 = new Car();

Thus, the following statement would echo equal:

If($my_car == $my_car2)
{
  echo "equal";
}

But, the following statement would not echo equal:

If($my_car === $my_car2)
{
  echo "equal";
}

The following two objects are equal, but not identical, because clone creates a new instance of the object Car:

$my_car = new Car();
$my_car2 = clone $my_car;

The following two objects are both equal and identical:

$my_car = new Car();
$my_car2 = $my_car;

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.