Re: [RFC] Readonly constructors
On Thu, May 22, 2025, at 17:01, Mihail Liahimov wrote:
> In PHP 8.1 the class read-on syntax was added, which allows you to create classes that are
> completely closed to changes. In addition, it allows you to write less boilerplate when declaring a
> property in the constructor.
>
> Before 8.1:
>
> class A
> {
> public function __construct(
> private readonly int $a,
> private readonly int $b,
> private readonly int $c,
> ) { }
> }
>
> After 8.1:
>
> readonly class A
> {
> public function __construct(
> private int $a,
> private int $b,
> private int $c,
> ) { }
> }
>
> But there are also scenarios where, for some reason, not all properties need to be readonly.
> For example, when we inherit from a non-readonly class or when our class has a state for some kind
> of memoization. In this case, the class is not readonly, and as a result, you have to write an extra
> boiler plate in the constructor. I would like to be able to declare many readon properties in the
> constructor in a way similar to readon classes.
>
> I suggest adding the ability to declare a constructor as a readonly. In this case, all the
> properties declared in it will be automatically readonly.
>
> class A extends NonReadonlyClass
> {
> public readonly function __construct(
> private int $a,
> private int $b,
> private int $c,
> ) { }
> }
>
> Yes, it looks a bit strange, but maybe someone will have other suggestions. Perhaps there is a
> more competent way to organize this idea.
Hello Mihail,
I feel like it is kinda that way on purpose? If you find yourself writing a constructor with a lot
of parameters that are a mix or readonly properties, it feels like that is a code smell. Either you
should consider decomposing the object into multiple single-purpose objects or rethink the
architecture in some way. For example:
> when our class has a state for some kind of memoization.
For example, in this case, you'd wrap the memoization state inside a mutable object and then
use that as a readonly property.
— Rob
Thread (2 messages)