Introduction
PHP has a comparison operator == using which a simple comarison of two objecs variables can be performed. It returns true if both belong to same class and values of corresponding properties are are same.
PHP's === operator compares two object variables and returns true if and only if they refer to same instance of same class
We use following two classes for comparison of objects with these oprators
Example
<?php class test1{ private $x; private $y; function __construct($arg1, $arg2){ $this->x=$arg1; $this->y=$arg2; } } class test2{ private $x; private $y; function __construct($arg1, $arg2){ $this->x=$arg1; $this->y=$arg2; } } ?>
two objects of same class
Example
$a=new test1(10,20); $b=new test1(10,20); echo "two objects of same class\n"; echo "using == operator : "; var_dump($a==$b); echo "using === operator : "; var_dump($a===$b);
Output
two objects of same class using == operator : bool(true) using === operator : bool(false)
two references of same object
Example
$a=new test1(10,20); $c=$a; echo "two references of same object\n"; echo "using == operator : "; var_dump($a==$c); echo "using === operator : "; var_dump($a===$c);
Output
two references of same object using == operator : bool(true) using === operator : bool(true)
two objects of different classes
Example
$a=new test1(10,20); $d=new test2(10,20); echo "two objects of different classes\n"; echo "using == operator : "; var_dump($a==$d); echo "using === operator : "; var_dump($a===$d);
Output
Output shows following result
two objects of different classes using == operator : bool(false) using === operator : bool(false)