Can a PHP Class be "final" and "readonly" at the Same Time?

A PHP class can be both, final and readonly, at the same time:

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

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

When you mark a class as final and readonly together, it means the following is true:

  • The order in which the final and readonly keywords appear (before the class keyword) does not matter;
  • All class properties in a final readonly class are implicitly readonly;
  • A final readonly class cannot be extended.

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.