Enums
Prerequisites: Traits
A PHP 8.1 enum defines a fixed, named set of values — safer than
a string or int constant, since the compiler rejects anything not
in the list.
enum Status
{
case Active;
case Inactive;
case Banned;
}
function describe(Status $status): string
{
return match ($status) {
Status::Active => 'User is active',
Status::Inactive => 'User is inactive',
Status::Banned => 'User is banned',
};
}
A backed enum attaches a scalar value to each case (useful for storing in a database):
enum Status: string
{
case Active = 'active';
case Inactive = 'inactive';
}
echo Status::Active->value; // "active"
echo Status::from('active') === Status::Active; // true