Constructors, Readonly and Enums
Constructor promotion declares properties in the constructor. readonly properties are set once. Backed enums have values, methods and from/tryFrom lookups.
Example
class Point { public function __construct(public readonly int $x = 0, public readonly int $y = 0) {} }
$p = new Point(3, 4);
echo $p->x + $p->y, "\n";
try { $p->x = 9; } catch (Error $e) { echo "readonly\n"; }
enum Status: string { case Draft = "draft"; case Live = "live"; public function label(): string { return ucfirst($this->value); } }
echo Status::from("live")->label(), " ", Status::tryFrom("x")?->value ?? "none", "\n";Result
7 readonly Live none
Exercise
Set once.
public int $id
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.