Home >Backend Development >PHP Tutorial >PHP comparison objects
PHP has a comparison operator ==, which can be used to perform a simple comparison of two objecs variables. Returns true if both belong to the same class and the values of the corresponding properties are the same.
PHP’s === Operator compares two object variables and returns true if and only if they refer to the same instance of the same class
We use the following two Class to compare objects with these operators
<?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; } } ?>
$a=new test1(10,20); $b=new test1(10,20); echo "two objects of same class"; echo "using == operator : "; var_dump($a==$b); echo "using === operator : "; var_dump($a===$b);
two objects of same class using == operator : bool(true) using === operator : bool(false)
$a=new test1(10,20); $c=$a; echo "two references of same object"; echo "using == operator : "; var_dump($a==$c); echo "using === operator : "; var_dump($a===$c);
two references of same object using == operator : bool(true) using === operator : bool(true)
$a=new test1(10,20); $d=new test2(10,20); echo "two objects of different classes"; echo "using == operator : "; var_dump($a==$d); echo "using === operator : "; var_dump($a===$d);
Output shows following result
two objects of different classes using == operator : bool(false) using === operator : bool(false)
The above is the detailed content of PHP comparison objects. For more information, please follow other related articles on the PHP Chinese website!