php对象比较大小,PHP比较对象-奇怪的行为

在测试我自己的模块进行验证时,我发现了某种问题.

我真的不知道发生了什么,也无法解释.

也许我很累,或者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告诉我们对象不相等-没错.

因此,现在我决定使用班级的对象.

我向构造函数提供了不同的参数(这些参数将设置为类属性)

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告诉我们对象是相等的,然后打印了这些对象,然后再次比较对象,但现在对象不相等.

您可以找到如下图所示的结果:

我没有使用任何魔术方法(构造方法除外),并且我无法显示ComparsionRule类的内容(被许可禁止)

另一个有趣的事实:

当我删除$_errorDefinitions属性时,它开始正常工作.当我更改属性顺序($_type和$_compareValue早于$_errorDefinitions定义)时类似

我不想获得替代解决方案,我只是想知道为什么它如此工作?

有人可以向我解释吗?

解决方法:

因为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对象之间提供任何有意义的比较.如果需要检查两个对象是同一实例,请使用===;否则,向类本身添加有意义的比较方法.

如果没有看到CompareRule的代码,我就无法真正猜出具体出了什么问题.我通常会假设某些对象属性正在进行某种惰性的初始化,因此这些属性不会在您的第一次比较中初始化(因此==将它们视为相等),而是通过转储对象来进行初始化.但是,如果不使用其他魔术方法,我认为这是不可行的.

标签:oop,compare,php,object

来源: https://codeday.me/bug/20191122/2059208.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值