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.

Reply via email to