Constants are no longer constant in PHP

I really hope that I am not opening a can of worms here because I think I have found something in PHP that I should not have. Something that should not exist: const mutable objects.

Yes, you read that correctly. Since PHP 8.1, any regular old object can be a constant, even mutable ones. Why is this a big deal? Well, because constants used to be constant and never change. This is no longer the case.

Here, have a quick taste:


class MyClass {
    public int $value = 1;
    public function set(int $value) { $this->value = $value; }

const MY_OBJECT = new MyClass();
// Equivalent to:
// define('MY_OBJECT', new MyClass());

echo MY_OBJECT->value . "\n";
echo MY_OBJECT->value . "\n";

// Prints:
// 1
// 2


Continue reading “Constants are no longer constant in PHP”

Elegant immutable object pattern in PHP

As many of you know, immutability is an extremely useful concept that makes code more predictable and generally easier to understand. Case in point, in PHP we have the mutable DateTime as well as DateTimeImmutable, the latter being recommended over the former.

And why is that?

Well, being an immutable object means that it can be passed around fearlessly without worrying about someone mutating it. No more guessing whether you should make a defensive copy or not. Plus, the API of DateTimeImmutable is not any worse than that of DateTime, so you get all of the benefits basically for free.

But it does not stop with DateTimeImmutable. We were always able to write our own immutable class types in PHP, and with the recently introduced readonly properties (PHP 8.1) and readonly classes (PHP 8.2) it is now easier than ever.

Continue reading “Elegant immutable object pattern in PHP”