DEV Community

pO0q 🦄
pO0q 🦄

Posted on

PHP 8.2: why using read-only classes?

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.

Top comments (2)

Collapse
 
po0q profile image
pO0q 🦄

wiki.php.net/rfc/readonly_amendments : although, it will be possible to extend read-only classes with "non read-only" classes in PHP 8.3

It seems that some advanced features you might need, like deep clone, do not work properly for now.

Collapse
 
nomadicjosh profile image
Joshua Parker

Great article. When I first read about readonly classes/properties, I was very excited, but I some how missed the change that is happening in 8.3. I think the change makes sense.