Comparing Objects

Objects can be compared using:

 

  • Comparison operator ==
    • Checks if the properties are the same 
  • Identity operator ===
    • Also checks if instances of the same class

This example creates a new object, clones it and then copies the original object using a simple assignment:

<?php
	class Person {

		public $name;
		public $now ;

		public function __construct() {
			echo "\$geek object instantiated.<br><br>";
			$this->now = time();
		}
		public function __clone(){
			//adding 1 to time to make cloned objects have a different $now value
			$this->now = time()+1;
		}
	}

	$geek = new Person;
	$geek->name = "Will";
	$techie = clone $geek;
	$imposter = $geek;

	if ($geek == $techie) {
		echo "\$geek and \$techie objects compare.<br>";
		} else {
			echo "\$geek and \$techie objects don't compare.<br>";
		}
	if ($geek == $imposter) {
		echo "\$geek and \$imposter objects compare.<br>";
		} else {
			echo "\$geek and \$imposter objects don't compare.<br>";
		}
	if ($geek === $techie) {
		echo "\$geek and \$techie objects are identical.<br>";
		} else {
			echo "\$geek and \$techie objects are not identical.<br>";
		}
	if ($geek === $imposter) {
		echo "\$geek and \$imposter objects are identical.<br>";
		} else {
			echo "\$geek and \$imposter objects are not identical.<br>";
		}

	echo "<pre>" . var_export($geek, TRUE) . "</pre>" ;
	echo "<pre>" . var_export($techie, TRUE) . "</pre>" ;
	echo "<pre>" . var_export($imposter, TRUE) . "</pre>" ;

?>

Save & refresh browser:

$geek object instantiated. 

 

$geek and $techie objects don't compare.
$geek and $imposter objects compare.
$geek and $techie objects are not identical.
$geek and $imposter objects are identical.

 

Person::__set_state(array(
'name' => 'Will',
'now' => 1372934803,
))

 

Person::__set_state(array(
'name' => 'Will',
'now' => 1372934804,
))

 

Person::__set_state(array(
'name' => 'Will',
'now' => 1372934803,
))

Leave a Reply