IntermediateLesson 10 of 16
Enums & readonly – PHP
Type-safe choice values and immutable objects – two highlights of PHP 8.1+.
An enum (since PHP 8.1) is a type with a fixed set of possible values. A *backed* enum has a string or int value for each case – ideal for database and form values. Enums may have methods and implement interfaces.
<?php
enum Status: string {
case Offen = "offen";
case Erledigt = "erledigt";
case Archiviert = "archiviert";
public function label(): string {
return match ($this) {
self::Offen => "To do",
self::Erledigt => "Done",
self::Archiviert => "Archived",
};
}
}
echo Status::Offen->value, "\n"; // offen
echo Status::from("erledigt")->label(), "\n"; // Done
var_dump(Status::tryFrom("xyz")); // NULL
echo count(Status::cases()), "\n"; // 3
foreach (Status::cases() as $s) {
echo $s->name, " "; // Offen Erledigt Archiviert
}from() throws a ValueError for an unknown value, tryFrom() returns null. As a parameter type (function setze(Status $s)), invalid values are ruled out.
readonly properties (8.1) can only be set once – in the constructor. This is how you build immutable value objects. As of PHP 8.2 you can even make the whole class readonly.
<?php
final class Money {
public function __construct(
public readonly int $cent,
public readonly string $waehrung = "EUR",
) {}
public function plus(Money $o): static {
return new static($this->cent + $o->cent, $this->waehrung);
}
}
$a = new Money(500);
$b = $a->plus(new Money(250));
echo $b->cent, "\n"; // 750
try {
$a->cent = 1;
} catch (Error $e) {
echo $e->getMessage(), "\n"; // Cannot modify readonly property Money::$cent
}
readonly class Punkt {
public function __construct(public float $x, public float $y) {}
public function mitX(float $x): static { return new static($x, $this->y); }
}
$q = (new Punkt(1, 2))->mitX(5);
echo $q->x, ",", $q->y, "\n"; // 5,2TipImmutable objects ("value objects") are safer: nobody can change them by accident, and you do not need getters. Changes simply return a new object.