Readonly Properties Can Have Default Values
A readonly property could not declare a default value. Until PHP 8.6, doing so was a fatal compile-time error, Readonly property Class::$prop cannot have default value. In PHP 8.6, a readonly property may declare a default value, which is used whenever the constructor does not explicitly initialize it. Assigning to the property once it already holds its default value, even from inside the constructor, still throws the usual Cannot modify readonly property error.
PHP code
<?php
class Point {
public readonly int $x = 0;
public function __construct(?int $x = null) {
if ($x !== null) {
$this->x = $x;
}
}
}
$p = new Point();
var_dump($p->x);
try {
$p2 = new Point(5);
var_dump($p2->x);
} catch (\Error $e) {
echo "Error: ".$e->getMessage()."\n";
}
?>
Before
PHP Fatal error: Readonly property Point::$x cannot have default value in /codes/readonlyPropertyDefaultValue86.php on line 4
After
int(0)
Error: Cannot modify readonly property Point::$x
PHP version change
This behavior changed in 8.6.