Comparing objects in Php

In this tutorial we are going to be looking at how to compare objects in PHP, first using the comparison operator (==) and then using identity operator (===).

As we shall see, each of the two operators behave differently based whether:

  • The objects are the same instance or different instances of a class
  • The object properties and their values are the same or not.

Object comparison using the equality operator ==

The "equal to" operator (==) compares if objects are holding the same property values and are instances of the same class. For example:

Example 1

<?php

class Spaceship {
  public $velocity = 23;
  public $name = "HMS Sytech Royal";
  public $enemy = false;

}


$command_ship = new Spaceship;
$service_ship = new Spaceship;

$result = ($command_ship == $service_ship);

var_dump($result); //> bool(true)


?>

In the example above, the comparison returned true because $command_ship and $service_ship are instances of the same class and their properties hold the same values.


Example 2

<?php

class Spaceship {
  public $velocity = 23;
  public $name = "HMS Sytech Royal";
  public $enemy = false;

}


$command_ship = new Spaceship;
$command_ship = "HMS Sytech Zimbabwe";

$service_ship = new Spaceship;

$result = ($command_ship == $service_ship);

var_dump($result); //> bool(false)


?>

This time, the comparison returned false because, even though $command_ship and $service_ship are instances of the same class, we changed the name property of object $command_ship and their properties no longer hold the same values. Changing the value of an instance variable in one object does not reflect in the other.

Object comparison using the strict equality operator ===

The "strictly equal to" operator (===) returns true only if the variables refer to the same instance of the same class. For example:

Example 1

<?php

class Spaceship {
  public $velocity = 23;
  public $name = "HMS Sytech Royal";
  public $enemy = false;

}


$command_ship = new Spaceship;
$service_ship = new Spaceship;

$result = ($command_ship === $service_ship);

var_dump($result);      //> bool(false) 


?>

The comparison returned false because the objects are not the same instance of the same class.

Example 2

<?php

class Spaceship {
  public $velocity = 23;
  public $name = "HMS Sytech Royal";
  public $enemy = false;

}


$command_ship = new Spaceship;
$service_ship = $command_ship;

$result = ($command_ship === $service_ship);

var_dump($result);      //> bool(true) 


?>

The comparison returned true because the objects are the same instance of the same class, since we literally assigned the reference of $command_ship to $service_ship.

[hfcm id=”1″]