Interview frequency: …
Short answer
A class modifier that makes all properties readonly automatically and prevents adding dynamic properties, ensuring the object's state stays fixed after construction.
Explanation
Immutable Value Objects are a foundation of Domain-Driven Design and safer programming. Before PHP 8.2, developers had to write readonly for every property. Marking a class as readonly class ensures that the engine requires every property to be assigned in the constructor and prevents it from being changed throughout the object's lifecycle.
Code example
readonly class Money {
public function __construct(
public int $amount,
public string $currency
) {}
}Common mistakes
- Trying to mark a class with untyped properties as readonly; the engine requires typed properties.
Follow-up questions
- What are Anonymous Classes, and when are they used in PHP?
- How does passing objects to PHP functions differ from passing ordinary variables by reference?