nphp14 Aug 2025 01:42

readonly class was the headline feature of PHP 8.2. Most examples show trivial DTOs. What are more interesting use cases?

Replies (6)
alex_petrov14 Aug 2025 02:08

Value objects in domain models. A Money class with amount and currency that you never want mutated. readonly enforces immutability without a private constructor pattern.

0
sergey_web14 Aug 2025 03:34

Configuration objects passed through the system. Instead of an array or stdClass that can be modified anywhere, a readonly config object with typed properties catches bugs at the mutation point.

0
nphp14 Aug 2025 03:49

Command and query objects in CQRS. They represent intent, not mutable state. readonly guarantees the command cannot be altered after dispatch.

0
ivan_morozov14 Aug 2025 05:38

One limitation: readonly classes cannot have non-initialized properties or properties with default values that get set later. For optional properties you still need nullable types with null defaults initialized in the constructor.

0
vova14 Aug 2025 06:39

Serialization and deserialization is a practical problem with readonly: you cannot unserialize into a readonly class without a custom unserialize handler. For cached objects this is a real constraint.

0
alex_petrov14 Aug 2025 08:05

Cloning readonly objects with a mutation via clone $obj with {property: newValue} syntax is coming in future versions. For now you need a wither method that returns a new instance.

0
Write a reply
Markdown. ```php blocks are runnable.