Enum Helpers for PHP
Published on by Paul Redmond
The release of PHP 8.1 brings native enumerations to PHP. The archtechx/enums composer package builds on native features and aims to make working with enums more lovable.
Using these library traits, you can add the following conveniences to your Enums in any PHP project:
- Invokable cases - get the value of a backed Enum by invoking it
- Names - return a list of case names in the enum
- Values - return a list of case values in the enum
- Options - return an associative array of case names and values
Given the above features, here are some examples from the package's readme file.
First up, here's how the InvokableCases
trait works:
// Invokableuse ArchTech\Enums\InvokableCases; enum TaskStatus: int{ use InvokableCases; case INCOMPLETE = 0; case COMPLETED = 1; case CANCELED = 2;} TaskStatus::INCOMPLETE(); // 0TaskStatus::COMPLETED(); // 1TaskStatus::CANCELED(); // 2
Next, here's how to get case names from enums:
use ArchTech\Enums\Names; enum TaskStatus: int{ use Names; case INCOMPLETE = 0; case COMPLETED = 1; case CANCELED = 2;} TaskStatus::names();// ['INCOMPLETE', 'COMPLETED', 'CANCELED']
The Values
trait can return an array of possible enum values:
use ArchTech\Enums\Values; enum TaskStatus: int{ use Values; case INCOMPLETE = 0; case COMPLETED = 1; case CANCELED = 2;} TaskStatus::values(); // [0, 1, 2]
Finally, the Options
trait returns an associative array of names and values:
use ArchTech\Enums\Options; enum TaskStatus: int{ use Options; case INCOMPLETE = 0; case COMPLETED = 1; case CANCELED = 2;} TaskStatus::options();// ['INCOMPLETE' => 0, 'COMPLETED' => 1, 'CANCELED' => 2]
You can learn more about this package, get full installation instructions, and view the source code on GitHub.