5

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

hosseio
  • 1,142
  • 2
  • 12
  • 25

2 Answers2

3

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.

iainn
  • 16,826
  • 9
  • 33
  • 40
  • But only objects, if I understand well. This does not apply to scalars, right? – hosseio Mar 07 '18 at 11:43
  • 1
    Yes, just for objects. For scalars, the general rule is that the two variables must have the same value and be of the same type. That is, they are the same value, *before* any ["type juggling"](http://php.net/manual/en/language.types.type-juggling.php) has taken place. – iainn Mar 07 '18 at 11:47
  • Since this doesn’t seem to be mentioned anywhere, you can obtain the expected result using strict equality by comparing their timestamps: `0 === $d->getTimestamp() - $e->getTimestamp()`. – Mat Aug 13 '23 at 14:08
2
$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

Bilal Ahmed
  • 4,005
  • 3
  • 22
  • 42