This is an old revision of the document!
PHP RFC: Readonly classes
- Date: 2021-08-04
- Author: Máté Kocsis kocsismate@php.net
- Status: Draft
- Target Version: PHP 8.2
- Implementation: https://github.com/php/php-src/pull/7305
Introduction
PHP 8.1 added support for readonly
properties via PHP RFC: Readonly properties 2.0.
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 typed instance properties of a class as readonly. Furthermore, it will prevent the usage of dynmacic properties.
Restrictions
A readonly class can only have typed properties.
As readonly static properties are not yet supported, readonly classes are forbidden to declare any static properties.
Inheritance
Similarly how overriding of readonly properties work, only a readonly class can extend a readonly class:
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. ReflectionClass::getModifiers()
will also report a ReflectionClass::IS_READONLY
flag.
Backward Incompatible Changes
None.
Vote
Add readonly classes as proposed?