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

Find out if a PHP class can be marked final and readonly together

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.

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