<?php
class Point {
public readonly string $name;
public function __construct(
public readonly int $x,
public readonly int $y,
) {}
public function setName(string $name): static
{
$this->name ??= $name;
return $this;
}
}
$p = new Point(3, 4);
$p->setName('Larry');
var_dump($p);
$p2 = new class extends Point {
public function __construct() {
$this->x = 3;
$this->y = 4;
$this->name = 'Larry';
}
};
var_dump($p2);
object(Point)#1 (3) {
["name"]=>
string(5) "Larry"
["x"]=>
int(3)
["y"]=>
int(4)
}
Fatal error: Uncaught Error: Cannot initialize readonly property Point::$x from scope Point@anonymous in /in/6MA6s:27
Stack trace:
#0 /in/6MA6s(25): Point@anonymous->__construct()
#1 {main}
thrown in /in/6MA6s on line 27
Process exited with code 255.
Output for 8.0.0 - 8.0.12
Parse error: syntax error, unexpected identifier "string", expecting variable in /in/6MA6s on line 4
Process exited with code 255.
Output for 7.4.0 - 7.4.25
Parse error: syntax error, unexpected 'string' (T_STRING), expecting variable (T_VARIABLE) in /in/6MA6s on line 4
Process exited with code 255.
Output for 7.3.0 - 7.3.32
Parse error: syntax error, unexpected 'readonly' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in /in/6MA6s on line 4
Process exited with code 255.