Can a readonly PHP Class be Extended?

Extending a readonly PHP class

Starting with PHP 8.2, classes can be declared as readonly (which can be extended from):

// PHP 8.2+
readonly class Foo { /* ... */ }

readonly class Bar extends Foo { /* ... */ }

However, there are two rules to keep in mind:

  1. Class that extends from a readonly class must also be declared readonly;
  2. A readonly class cannot extend a non-readonly class.

These rules exist to prevent subclasses from breaking the semantics of the parent class.

Only readonly Classes Can Extend a readonly Class

A subclass that extends from a readonly class must also be declared as readonly. To demonstrate this, consider for example, the following:

// PHP 8.2+
readonly class Foo { /* ... */ }

// Fatal error: Non-readonly class Bar cannot extend readonly class Foo ...
class Bar extends Foo { /* ... */ }

readonly Classes Cannot Extend a Non-Readonly Class

A subclass that's marked as readonly can only extend a readonly parent. To demonstrate this, consider for example, the following:

// PHP 8.2+
class Foo { /* ... */ }

// Fatal error: Readonly class Bar cannot extend non-readonly class Foo ...
class Bar extends Foo { /* ... */ }

Hope you found this post useful. It was published . Please show your love and support by sharing this post.