What are readonly properties in PHP 8.1?
Why Interviewers Ask This
Mid-level PHP roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.
Answer
Readonly properties (PHP 8.1) can only be initialized once — typically in the constructor — and cannot be modified after that. Attempting to write to a readonly property after initialization throws an Error. class User { public function __construct(public readonly string $name, public readonly int $id) {} }. Combined with constructor promotion, this creates immutable value objects with minimal boilerplate. PHP 8.2 added readonly classes — marking the class as readonly makes all its promoted and explicitly declared properties readonly automatically. Readonly properties are particularly useful for DTOs (Data Transfer Objects), value objects, and event objects where immutability is a design requirement.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a PHP codebase.