我有两个DateTimeImmtable
对象,并且期望它们是相同的,我很惊讶地发现它们不是。 即,为什么是以下false
?
<?php
$d = new DateTimeImmutable('2018-01-01');
$e = new DateTimeImmutable('2018-01-01');
var_dump($d === $e);
当然,$d == $e
评估结果为true
这与DateTimeImmutable
对象无关,只是 PHP 如何处理对象比较。从手册:
使用标识运算符 (===( 时,当且仅当对象变量引用同一类的同一实例时,它们才相同。
使用此运算符比较任何两个不同的实例将始终返回 false,而不考虑任何属性的值。
$d = new DateTimeImmutable('2018-01-01');
$e = new DateTimeImmutable('2018-01-01');
var_dump($d);
var_dump($e);
输出为
object(DateTimeImmutable)[1]
public 'date' => string '2018-01-01 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Paris' (length=12)
object(DateTimeImmutable)[2]
public 'date' => string '2018-01-01 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Paris' (length=12)
根据PHP手册:他们将对象作为不同的对象或实例处理,当您比较两个对象时,他们将2个对象处理为不同的对象
当你使用===
来比较对象或实例(同一类的两个实例(时,它们将这些对象作为不同的对象处理,结果是假的