在测试我自己的模块以进行验证时,我发现了一些问题。 我真的不知道发生了什么,我无法解释。
也许是我太累了,或者 PHP 实在是太崩溃了。 谁能告诉我哪里出了问题?
我想比较对象(因为我想检查数组中是否已经存在该对象)
在PHP手册中我们可以看到:
Comparing Objects
In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language).
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
所以,让我们创建简单的代码来使用它
class A
{
protected $property;
public function __construct($value)
{
$this->property = $value;
}
}
$object1 = new A('ABC');
$object2 = new A('XYZ');
// Instances are not equal because of different value of property
var_dump($object1 == $object2); // Will return bool(false)
好的,PHP 告诉我们对象不相等 - 没错。
所以现在我决定使用我类(class)的对象。 我为构造函数提供了不同的参数(这些参数将被设置为类属性)
echo "Start";
// Creating an instance of class with some parameters
// Each of parameter will be stored as class property
$object1 = new ComparsionRule('ABadasdC', ComparsionRule::LESS_THAN_OR_EQUAL);
// Creating an instance of class with some different parameters
// Each of parameter will be stored as class property
$object2 = new ComparsionRule('XYZ', ComparsionRule::NOT_EQUAL_TO);
// Two instances should not be equal (false expected)
var_dump($object1 == $object2); // Will return bool(true)
// Printing content of first object
var_dump($object1);
// Printing content of second object
var_dump($object2);
// Checking the expression again
// Two instances should not be equal (false expected)
var_dump($object1 == $object2); // Will return bool(false)
echo "End";
die;
结果令人惊讶,因为首先 PHP 告诉我们对象相等,然后打印这些对象,之后它再次比较对象但现在对象不相等。
您可以找到如下图所示的结果:
我没有使用任何魔法方法 (excepts construct) 而且我无法显示 ComparsionRule 类的内容 (许可证禁止)
另一个有趣的事实:
当我删除 $_errorDefinitions 属性时,它开始正常工作。当我更改属性顺序时类似($_type 和 $_compareValue 定义早于 $_errorDefinitions)
我不想获得替代解决方案我只是想知道为什么它会这样工作?
谁能给我解释一下?
最佳答案
因为 PHP 太疯狂了!
<?php
class A {
public $property;
public function __construct($value) {
$this->property = $value;
}
}
$object1 = new A('Hello World');
$object2 = new A(0);
var_dump($object1 == $object2);
不要依赖 ==
来提供 PHP 对象之间任何有意义的比较。如果需要检查两个对象是同一个实例,使用===
;否则向类本身添加一个有意义的比较方法。
如果没有看到 ComparisonRule
的代码,我真的无法冒险猜测具体出了什么问题。我通常假设某些对象属性正在进行某种惰性初始化,这样属性就不会在您的第一次比较中被初始化(因此 ==
将它们视为相等),但是通过转储对象进行初始化。但是,如果不使用更多神奇的方法,我认为这是不可行的。
关于PHP 比较对象 - 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20566770/