2

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?

Duncan Lukkenaer
  • 12,050
  • 13
  • 64
  • 97

1 Answers1

3

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.

Duncan Lukkenaer
  • 12,050
  • 13
  • 64
  • 97