PHP 8.2: why using read-only classes?

spO0q 🐒 - Aug 5 '23 - - Dev Community

PHP 8.2 introduced read-only classes. In PHP 8.1, you can already define read-only properties that cannot be overwritten from outside.

Now, you can automatically declare all class properties as readonly. All the previous rules (read-only properties) will apply.

Hum, why making all properties read-only?

To prevent dynamic properties (deprecated), even with the special attribute #[AllowDynamicProperties], for example.

PHP 8.2 syntax for read-only classes

readonly class Test {
    public string $property;
}
Enter fullscreen mode Exit fullscreen mode

You can't use it for everything

Unless it's a standard class or an abstract, you cannot use the readonly keyword with the following structures:

  • Interfaces
  • Enums
  • Traits

You would get a fatal error.

Type safety vs. immutability

Whether it's for read-only properties or entire read-only classes, you can only use the readonly keyword with typed properties.

You also cannot circumvent this mechanism with inheritance. Child classes will have to be read-only too.

However, read-only does not mean immutable, as if your properties hold objects, these objects can still change. It's essential to keep that in mind.

Wrap up

The classic usage would be for object values. You write less code, but it does not guarantee immutability everywhere.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .