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:
- Class that extends from a
readonlyclass must also be declaredreadonly; - A
readonlyclass 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 { /* ... */ }
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.