PHP Enum done right
Easy way to use enumerated values in PHP.
Please, use composer.
composer require spareparts/enum
/**
* @method static OPEN
* @method static CLOSED
*/
class WindowStateEnum extends \SpareParts\Enum\Enum
{
}
// obtain enum value
$state = WindowStateEnum::OPEN();
// assign enum value
$windows->state = WindowStateEnum::CLOSED();
// compare enum values
if ($window->state === WindowStateEnum::OPEN()) {
....
}
// use enum to guard method parameters
function changeWindowState(WindowStateEnum $newState) {
...
}
- extend Enum class
- Annotate enum class with @method annotations describing Enum values
There are two possible ways to use enum values, with first one being preferred.
- using static methods with same name as your desired value.
This works with help from magic __callStatic method, meaning you do not have to add any methods manually.
$state = WindowStateEnum::OPEN();
This method is preferred, as it nicely shows its intended value without having to use weakly guarded strings.
Important tip: To have values correctly autocompleted, use @method annotations, like this:
/**
* @method static OPEN
* @method static CLOSED
*/
class WindowStateEnum extends \SpareParts\Enum\Enum
{
}
This way, your IDE should know WindowStateEnum
has 2 methods OPEN and CLOSE and correctly hint on their names. In case you are using IDE without support for @method annotations, you can always just add those methods "for real" :)
- using
instance()
method with desired value as instance parameter
$state = WindowStateEnum::instance('OPEN');
There is nothing wrong with this approach, but mistakes/typos can be easily made.
In case you ask for value that is not in the enum values, an InvalidEnumValueException exception is thrown.
try {
$window->setState(WindowStateEnum::FLYING());
} catch (InvalidEnumValueException $e) {
echo "This is not a correct state for window to be in!";
}
You can check for enum belonging to any of an enum group / set like this:
if ($state->isAnyOf([Window::OPEN(), Window::CLOSED()]));