PHP比较对象
介绍
PHP具有比较运算符 ==,使用该运算符可以对两个objecs变量进行简单的比较。如果两者都属于同一类并且对应属性的值相同,则返回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\n"; 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\n"; 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\n"; 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)
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短