I have two DateTimeImmtable
objects, and expecting them to be identical I am surprised to see they are not. Ie, why is the following false
?
<?php
$d = new \DateTimeImmutable('2018-01-01');
$e = new \DateTimeImmutable('2018-01-01');
var_dump($d === $e);
Of course $d == $e
evaluates to true
It's nothing to do with DateTimeImmutable
objects, it's just how PHP deals with object comparison. From 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.
Comparing any two different instances using this operator will always return false, regardless of the values of any properties.
$d = new \DateTimeImmutable('2018-01-01');
$e = new \DateTimeImmutable('2018-01-01');
var_dump($d);
var_dump($e);
the output is
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)
As per PHP manual: they deals with object as a different object or instance, when you compare two objects they deals 2 objects as a different objects
when you used ===
to compare the object or instance( Two instances of the same class) then they deals these objects as a different objects and the result is false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With