PHP theorytheory 0/50 · 0%
OOP · medium

22. Readonly Properties

Immutable object state.

PHP 8.1 added the readonly modifier for typed properties, allowing them to be initialized once (typically in the constructor) and never modified afterward. Attempting to reassign a readonly property throws an Error.

Readonly properties are commonly combined with constructor promotion to build immutable value objects and DTOs concisely.

Check your understanding

  1. 1. What happens when you try to modify a readonly property after initialization?

  2. 2. readonly properties are most useful for building what?