hosseio
hosseio

Reputation: 1222

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

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

Upvotes: 7

Views: 1445

Answers (2)

Bilal Ahmed
Bilal Ahmed

Reputation: 4076

$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

Upvotes: 2

iainn
iainn

Reputation: 17433

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.

Upvotes: 5

Related Questions