Below you will find pages that utilize the taxonomy term “Immutability”
Effective immutability with PHPStan
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:
Introducing the ConvenientImmutability package
As was the case with the SymfonyConsoleForm library, I realized I had not taken the time to properly introduce another library I created some time ago: ConvenientImmutability. This one is a lot simpler, but from a technical standpoint I think it might be interesting to at least talk a bit about the considerations that went into it.
For starters, it’s important to keep in mind that I don’t think you’ll actually need to use this library. Of course, I’ll explain why. But first: what is ConvenientImmutability about?