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
finalandreadonlykeywords appear (before theclasskeyword) does not matter; - All class properties in a
finalreadonlyclass are implicitlyreadonly; - A
finalreadonlyclass 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.