我有两个DateTimeImmtable
个对象,期望它们是相同的,我很惊讶它们不是。即,为什么以下false
?
<?php
$d = new \DateTimeImmutable('2018-01-01');
$e = new \DateTimeImmutable('2018-01-01');
var_dump($d === $e);
当然$d == $e
评估为true
答案 0 :(得分:2)
它与DateTimeImmutable
个对象无关,它只是PHP处理对象比较的方式。来自the manual:
当使用标识运算符(===)时,当且仅当它们引用同一类的同一实例时,对象变量才相同。
使用此运算符比较任意两个不同的实例将始终返回false,无论任何属性的值如何。
答案 1 :(得分:2)
$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个对象作为不同的对象处理
当您使用===
比较对象或实例(同一个类的两个实例)时,它们将这些对象作为不同的对象处理,结果为false