phpphp-8.1

PHP public readonly properties vs private field with getter


PHP 8.1 introduces readonly class properties. For example, before I would write:

class User
{
    public string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public getName(): string {
        return $this->name;
    }
}

But now I can do:

class User
{
    public function __construct(
        public readonly string $name,
    ) {}
}

The latter is obviously much more compact, so I am wondering if this syntax completely replaces the former for every use case, or are there still cases where the "old" syntax should be preferred?


Solution

  • One advantage of the "old" way is that you can choose different access levels for the getter and setter, whereas a readonly field has only a single access level. E.g. when you want your setter to be protected.

    Another advantage of using getters is that it allows you to change the implementation without changing the class interface.

    Furthermore readonly properties as the name suggests can be set only once very much like JavaScript const variables. Depending on context this might be a desirable or a bad thing. Certain properties should be only set once and attempts to set them again should be flagged.

    Although being "syntax candy" public readonly properties do have their merit.