DEV Community

spO0q 🐒
spO0q 🐒

Posted on

PHP 8.1: why using read-only properties?

PHP 8.1 introduced read-only properties, which allows creating class properties that cannot be overwritten with less code.

What are read-only properties?

Read-only properties are initialized once and are not supposed to change after.

PHP programmers have been using various techniques to create such properties before PHP 8.1, for example, using value objects with no setters and only public getters.

You may think that constants are even simpler, but it's a very specific type that cannot cover all cases.

With PHP 8.1, the language ensures such properties cannot be changed from outside.

Read-only properties syntax in PHP 8.1

Using the readonly keywords and the constructor promotion, we can declare such properties in one line:

class Foo {
    public function __construct(public readonly string $property) {}
}
Enter fullscreen mode Exit fullscreen mode

Wrap up

Read-only properties are handy in value objects. If you combine it with constructor promotion, the code will be more readable.

Top comments (0)