Readonly Class Must Match Its Parent

../_images/readonly-class-inheritance.png

PHP 8.2’s readonly class looks like sugar for marking every property readonly at once, but it comes with the same strict rule than plain readonly properties: the whole inheritance chain must agree.

This is true even if there are no properties in any class.

A non-readonly class cannot extend a readonly class, since that would let the child sneak in a mutable property.

The reverse also fails: a readonly class cannot extend a non-readonly one, since the parent might already have a mutable property.

It is not possible to mix and match: making all properties readonly does not prevent the engine to ask for the class to be also readonly because of the parent.

There is no partial opt-in: readonly-ness is a property of the whole class hierarchy, not of one class in it.

The most flexible way is to keep the class mutable, and make properties readonly piecemeal.

See Also

PHP Error Messages

PHP Features