Enums deep dive

Backed values

A backed enum stores a string or int behind each case. The scalar fits database fields and JSON values without extra mapping.

Read the scalar through the value property. Rebuild the case from a scalar with from or tryFrom.

enum Role: string { case Admin = "admin"; case Guest = "guest"; }

Methods

Enums can hold methods much like classes do. Labels and checks live next to the cases they describe.

Inside a method, $this points at the current case and gives access to value and name.

enum Role: string { case Admin = "admin"; case Guest = "guest"; public function label(): string { return "Role: " . $this->value; } }

TryFrom

The from method throws when the scalar matches no case, while tryFrom returns null instead. User input and database rows deserve the soft form.

Check the result for null before moving on. That one check replaces long validation chains.

$role = Role::tryFrom("admin"); if ($role === null) { echo "Unknown role"; }

JsonSerializable

Backed enums turn into JSON through their scalar value when the enum uses JsonSerializable. API output stays stable and easy to read.

Return value from jsonSerialize and let json_encode handle the rest.

enum Role: string implements JsonSerializable { case Admin = "admin"; case Guest = "guest"; public function jsonSerialize(): mixed { return $this->value; } }

Next: Clone objects

Автор статьи: Arthur Isaev