rfc:readonly_classes

This is an old revision of the document!


PHP RFC: Readonly classes

Introduction

PHP 8.1 added support for readonly properties via PHP RFC: Readonly properties 2.0. However, it's still not easy to declare (quasi-)immutable classes, especially if they contain many properties. Therefore, this RFC proposes to add support for readonly classes.

Proposal

The usage of the readonly modifier added by PHP RFC: Readonly properties 2.0 is extended to classes:

readonly class Test {
    public string $prop;
}

Doing so will implicitly mark all instance properties of a class as readonly. Furthermore, it will prevent the usage of dynamic properties.

readonly class Foo
{
    public int $bar;
 
    public function __construct() {
        $this->bar = 1;
    }
}
 
$foo = new Foo();
$foo->bar = 2;
// Cannot modify readonly property Foo::$bar
 
$foo->baz = 1;
// Cannot create dynamic property Foo::$baz

Restrictions

A readonly class can only have typed properties, since untyped properties cannot be marked as readonly.

As static properties are also not covered by the Readonly properties RFC, readonly classes cannot declare them either.

Inheritance

Similarly how overriding of readonly properties work, only a readonly class can extend a readonly parent:

class A {}
readonly class B extends A {}

Both of the following are illegal:

readonly class A {}
class B extends A {}
class A {}
readonly class B extends A {}

Reflection

A ReflectionClass::isReadOnly() method is added, which reports whether a class is declared as read-only. Additionally, ReflectionClass::getModifiers() will also include the ReflectionClass::IS_READONLY flag.

Backward Incompatible Changes

None.

Vote

Add readonly classes as proposed?

rfc/readonly_classes.1637595732.txt.gz · Last modified: 2021/11/22 15:42 by kocsismate