Effective immutability with PHPStan

Posted on by Matthias Noback

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:

New book: Recipes for Decoupling

Posted on by Matthias Noback

My new book Recipes for Decoupling is 100% complete and available now!

And now some other news related to this book.

DDD entities and ORM entities

Posted on by Matthias Noback

I was tweeting something about having separate "DDD" and "ORM" entities in a project in a project, and that I don't understand this. There were some great comments and questions, thanks a lot for that! To be honest, I understand more about it now. In this article I'll try to provide some more information about this.