PHP › OOP
How does the readonly property modifier introduced in PHP 8.1 help enforce immutability for specific class properties?
IntermediateAnswer
The readonly modifier lets you declare a property that can only be assigned a value once, typically within the constructor, and any subsequent attempt to modify that property from anywhere, including from within the class itself, throws an error, which is valuable for creating immutable value objects where a property's value should genuinely never change after the object is first created, catching accidental mutation bugs at the point they occur rather than allowing them to silently happen.
class Point {
public function __construct(public readonly float $x, public readonly float $y) {}
}
$point = new Point(3.0, 4.0);
// $point->x = 5.0; // Throws an ErrorReal-world example A coordinate system uses readonly properties for its Point class, guaranteeing that once a point is created, its x and y values can never be accidentally modified elsewhere in the codebase, providing strong confidence in the object's immutability.