This article is about a topic that didn't make the cut for my latest book, Recipes for Decoupling. It still contains some useful ideas I think, so here it is anyway!
DateTimeImmutable is mutable
I don't know where I first heard it, but PHP's DateTimeImmutable
is not immutable:
<?php
$dt = new DateTimeImmutable('now');
echo $dt->getTimestamp() . "\n";
$dt->__construct('tomorrow');
echo $dt->getTimestamp() . "\n";
The result:
1656927919
1656972000
Indeed, DateTimeImmutable
is not really immutable because its internal state can be modified after instantiation. After calling __construct()
again, any existing object reference will have the modified state as well. But an even bigger surprise might be that if a constructor is public
, it's just another method that you can call. You're not supposed to, but you can. Which is another reason to make the constructor of non-service objects private
and add a public static constructor to a class that you want to be immutable: