PHP 8.1 backed enums — practical patterns beyond basic usage
Native enums landed in PHP 8.1 and most examples show the basic definition. Here are patterns I use in production that are less obvious.
Adding methods to enums is the part most people skip. An enum with methods replaces a whole class of switch statements that would otherwise be scattered across the codebase.
Implementing interfaces on enums is another underused feature:
One gotcha I ran into: you cannot use new on an enum, and you cannot add regular properties to them. If you need instance state alongside enum cases, you need a separate class. Trying to add public string $description as a property to an enum will produce a parse error.
The workaround people use is a method that returns the associated data from a hardcoded match, which you can see in the examples above. Not ideal for large datasets, but for a fixed set of states it is perfectly fine.
```php blocks are runnable.