我正在对对象列表进行严格比较,只是为了识别可能已更改的对象,例如:
if ($oldValue !== $newValue)
在某些情况下
$oldValue
和 $newValue
是 DateTime
对象。调试我的应用程序在比较它们之前,我得到了以下两个值的输出:
DateTime Object ( [date] => 2017-04-24 00:00:00.000000 [timezone_type] => 3 [timezone] => UTC )
DateTime Object ( [date] => 2017-04-24 00:00:00.000000 [timezone_type] => 3 [timezone] => UTC )
为什么我的比较/条件仍然正确?
最佳答案
在 PHP 中比较对象时,===
运算符不比较值。 It compares instances .这意味着除非两个对象都指向同一个对象,否则它们并不严格相等。
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 (values are compared with ==), and are instances of the same class.
When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.
关于php - DateTime 对象的严格比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43592329/