🐘 PHP
Intermediate
What are readonly properties in PHP 8.1?
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.