What Does it Mean for a PHP Class to be "final" and "readonly"?

When a PHP class is marked as final and readonly, it means that:

  • All class properties are implicitly readonly (because of the class being marked as readonly);
  • The class cannot be extended (because of the class being marked as final).

For example, let's suppose you have the following final readonly class:

// PHP 8.2+
final readonly class Shape {
    public function __construct(
        public string $name,
        public int $sides,
    ) {}

You could use it in the following way:

$shape = new Shape('triangle', 3);
echo $shape->name . ' has ' . $shape->sides . ' sides'; // "triangle has 3 sides"

If you try to assign a value to any object property, it would throw the following error (as all properties are implicitly readonly):

// PHP 8.2+
// Fatal error: Uncaught Error: Cannot modify readonly property Shape::$name
$shape->name = 'circle';

If you try to extend the class, then it would throw the following error (as the class is marked as final):

// Fatal error: Class Triangle cannot extend final class Shape
readonly class Triangle extends Shape {}

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.