为什么 php (===) 中的相同运算符因 DateTimeImmutable 对象而失败?

Why identical operator in php (===) fails with DateTimeImmutable objects?

我有两个 DateTimeImmtable 对象,并期望它们是相同的,但我很惊讶地发现它们不是。即,为什么是下面的false?

<?php
$d = new \DateTimeImmutable('2018-01-01');
$e = new \DateTimeImmutable('2018-01-01');

var_dump($d === $e);

当然 $d == $e 的计算结果为 true

这与 DateTimeImmutable 对象无关,只是 PHP 处理对象比较的方式。来自 the manual:

When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

无论任何属性的值如何,使用此运算符比较任何两个不同的实例总是 return 错误。

$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 个对象作为不同的对象处理

当您使用 === 比较对象或实例(相同的两个实例 class)时,它们将这些对象作为不同的对象处理,结果为假