Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 958
hosseio Avatar asked Mar 07 '18 11:03

hosseio


2 Answers

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.

like image 107
iainn Avatar answered Sep 20 '22 16:09

iainn


$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

like image 27
Bilal Ahmed Avatar answered Sep 16 '22 16:09

Bilal Ahmed