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.
Readonly static properties are not supported. This is a technical limitation, in that it is not possible to implement readonly static properties non-intrusively. In conjunction with the questionable usefulness of readonly static properties, this is not considered worthwhile at this time.
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?