PHP 比较对象
phpserver side programmingprogramming更新于 2025/7/18 22:22:17
简介
PHP 有一个比较运算符 ==,可用于对两个对象变量进行简单的比较。如果两个对象变量属于同一个类,且对应属性的值相同,则返回 true。
PHP 的 === 运算符用于比较两个对象变量,当且仅当它们指向同一个类的同一个实例时才返回 true。
我们使用以下两个类来使用这些运算符比较对象。
示例
<?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);
输出
输出显示以下结果
two objects of different classes using == operator : bool(false) using === operator : bool(false)

