PHP/enum
< PHP
Jump to navigation
Jump to search
|
PHP enum support
|
Examples
| "Basic" enum | "Backed" enum |
|---|---|
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
|
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
|
Methods
| kind of thing | name & args | returns | defined in | description |
|---|---|---|---|---|
| static function | cases() |
array | UnitEnum |
returns a packed array of all defined cases, in order of declaration |
| static function | tryFrom(int|string $value) |
?static | BackedEnum |
same as from(), but returns NULL if not found (instead of erroring)
|
| static function | from(int|string $value) |
static | BackedEnum |
same as tryFrom, but throws an error if not found
|
| dynamic property | $name | string | UnitEnum |
the name of the case (case-sensitive) |
| dynamic property | $value | int or string | BackedEnum |
the value of the case |
Caveats
Enums are similar to objects in that:
- An
enumcase will pass theis_object()test. (I think.) - They may implement interfaces.
- Code in their methods may use
self::and$this->. - The
::classmagic constant works.
Enums are different from objects in that:
- They cannot be extended, or extend other entities.
- They can't have constructors or destructors.
- They can't have static properties.
- The
::classmagic constant exists on individual cases (enum instances) as well. - An
enumcan't be instantiated like an object; individual cases are similar to singleton objects.- Cases also provide the
::classmagic constant. (I don't think this works on regular objects.)
- Cases also provide the
Not sure if enum cases can be used as switch cases (to be checked).
Documentation
Note that enums can be cast directly to arrays.
- Enumerations:
- Demiclasses:
3rd party
Sample Code
To get a UnitEnum enum from a case name (equivalent to from()/tryFrom()):
- constant("<enum name>::{$value}")
Tests
- is an
enumcase an object (is_object)? [YES] - is an
enumseen asis_a UnitEnum? [YES] - is an
enumaninstanceof UnitEnum? [YES] - is an
enumaninstanceof enum? [no]