CKTIS / PHP
Keyword readonly
A typed readonly property permits initial assignment and prevents subsequent modification of the property itself.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
public readonly object $details;A typed readonly property permits initial assignment and prevents subsequent modification of the property itself. An object stored there may still mutate internally. PHP 8.3 allows reinitialization during __clone(). In PHP 8.4 readonly properties have protected(set) initialization scope by default. Since PHP 8.2 a readonly class marks all declared properties readonly and rejects dynamic properties.
class Holder {public function __construct(public readonly object $details){}}
$h=new Holder((object)["n"=>1]); $h->details->n=3; echo $h->details->n; try{$h->details=(object)[];}catch(Error $e){echo " ",get_class($e);}
readonly class Point {public function __construct(public int $x){}} $p=new Point(2); try{$p->y=3;}catch(Error $e){echo "\n",$p->x," ",get_class($e);}
3 Error
2 Error
Examples
<?php
class Holder {public function __construct(public readonly object $details){}}
$h=new Holder((object)["n"=>1]); $h->details->n=3; echo $h->details->n; try{$h->details=(object)[];}catch(Error $e){echo " ",get_class($e);}
readonly class Point {public function __construct(public int $x){}} $p=new Point(2); try{$p->y=3;}catch(Error $e){echo "\n",$p->x," ",get_class($e);}
Result
3 Error 2 Error