Since PHP 8.1 there are implemented native readonly properties
Documentation
You can initialize readonly property only once during the declaration of the property.
class Test {
public readonly string $prop;
public function __construct(string $prop) {
$this->prop = $prop;
}
}
--
class Test {
public function __construct(
public readonly string $prop,
) {}
}
Trying to modify the readonly propety will cause following error:
Error: Cannot modify readonly property Test::$prop
Update PHP 8.2
Since PHP 8.2 you are able to define as readonly a whole class.
readonly class Test {
public string $prop;
public function __construct(string $prop) {
$this->prop = $prop;
}
}
readonlyas a keyword for properties, would make life a lot easier instead of constantly defining getters or using the Proxy Patternreadonlywas oficially added in PHP8.1 and yes it can be used as @shadowhand suggested + even more it can be used in the constructor-style definition of properties - see stackoverflow.com/a/68376398/1835470 below