Skip to main content
A readonly property in PHP is a class property that can be initialized exactly once. After initialization, its value becomes immutable for the lifecycle of the object, and any subsequent attempt to modify or unset it will result in a fatal Error.

Syntax and Initialization

The readonly modifier is applied to a property declaration. It can be used alongside visibility modifiers (public, protected, private).
It is frequently combined with constructor property promotion for brevity:

Strict Technical Constraints

1. Explicit Typing Requirement A readonly property must have an explicit type declaration. Untyped properties cannot be marked readonly. If any type is acceptable, the mixed type must be explicitly declared.
2. Scope of Initialization A readonly property can only be initialized from within the scope of the class where it is declared. It cannot be initialized from outside the class, even if the property is public.
3. Static Modifier Prohibition Readonly properties cannot be declared as static. The readonly modifier is strictly tied to instance properties. Attempting to combine them results in a fatal error.
4. No Default Values Readonly properties cannot specify a default value in their declaration. A default value constitutes an initialization, which would permanently lock the property to that value for all instances.
5. Unsetting is Prohibited Once initialized, a readonly property cannot be destroyed using unset().
6. Pass-by-Reference Restriction Readonly properties cannot be passed by reference to functions or methods, as this would create a vector for bypassing the immutability constraint.

Shallow Immutability

The readonly modifier enforces a strict binding between the property and its assigned value. However, if the assigned value is an object, the internal state of that referenced object remains mutable. The readonly constraint prevents assigning a new object to the property, but does not make the referenced object itself immutable.

Readonly Classes (PHP 8.2+)

The readonly modifier can be applied to the class declaration itself. This implicitly marks every declared property within the class as readonly and prevents the creation of dynamic properties.

Reinitialization during Cloning (PHP 8.3+)

As of PHP 8.3, readonly properties can be reinitialized exclusively within the __clone() magic method. This allows for deep cloning of objects containing readonly properties.
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More