Enums (PHP 8.1)
An enum is a fixed list of allowed values. It replaces loose strings and magic numbers.
PHP · Enums (PHP 8.1)Intermediate
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
public function label(): string
{
return ucfirst($this->value);
}
public function isPublic(): bool
{
return $this === self::Published;
}
}
$s = Status::from('published'); // throws on an unknown value
$t = Status::tryFrom('oops'); // null instead
echo $s->label(); // Published
var_dump($s->isPublic(), $t); // true, NULL
echo count(Status::cases()); // 3enumphp8types