Enums
| Define an enum | |
| Backed enums | |
| Methods on enums | |
| Match on enums |
Define an enum
An enum lists a fixed set of allowed cases. It replaces loose strings with values the engine can check.
Type hints with the enum name reject every value outside the list.
enum Status { case Draft; case Published; }
Backed enums
A backed enum stores a string or int behind each case. This form fits database fields and JSON values.
Read the scalar with the value property and rebuild with the from method.
enum Role: string { case Admin = "admin"; case Guest = "guest"; }
Methods on enums
Enums can hold methods like classes do. Use them to place labels and checks next to the cases.
Inside a method, $this points to the current case and gives access to its value.
enum Role: string { case Admin = "admin"; case Guest = "guest"; public function label(): string { return "Role " . $this->value; } }
Match on enums
Expression match pairs well with enums because it checks all cases in one place.
Each arm names one case and returns a value without long chains of conditions.
enum Status { case Draft; case Published; } function describe(Status $s): string { return match ($s) { Status::Draft => "Not ready", Status::Published => "Live", }; }
Next: Magic methods
Article author: Arthur Isaev