PHP/enum: Difference between revisions
from HTYP, the free directory anyone can edit if they can prove to me that they're not a spambot
No edit summary |
No edit summary |
||
| Line 1: | Line 1: | ||
{{fmt/title|PHP enum support}} | {{fmt/title|PHP enum support}} | ||
==Examples== | |||
{| class=wikitable | |||
! "Basic" enum || "Backed" enum | |||
|- | |||
| | |||
<syntaxhighlight lang=php> | |||
enum Suit | |||
{ | |||
case Hearts; | |||
case Diamonds; | |||
case Clubs; | |||
case Spades; | |||
} | |||
</syntaxhighlight> | |||
| | |||
<syntaxhighlight lang=php> | |||
enum Suit: string | |||
{ | |||
case Hearts = 'H'; | |||
case Diamonds = 'D'; | |||
case Clubs = 'C'; | |||
case Spades = 'S'; | |||
} | |||
</syntaxhighlight> | |||
|} | |||
==Methods== | ==Methods== | ||
{| class="wikitable sortable" | {| class="wikitable sortable" | ||
| Line 15: | Line 40: | ||
| dynamic property || $value || int or string || ({{l/php/native|BackedEnum}}) || the name of the case (caps are preserved) | | dynamic property || $value || int or string || ({{l/php/native|BackedEnum}}) || the name of the case (caps are preserved) | ||
|} | |} | ||
==Documentation== | ==Documentation== | ||
Note that enums can be cast directly to arrays. | Note that enums can be cast directly to arrays. | ||
* Enumerations: | * Enumerations: | ||
** [https://www.php.net/manual/en/language.types.enumerations.php variable type] | ** [https://www.php.net/manual/en/language.types.enumerations.php variable type] | ||
Revision as of 22:50, 23 August 2024
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 | Template:L/php/native | |
| static function final | tryFrom(int|string $value) |
?static | Template:L/php/native | |
| static function final | from(int|string $value) |
static | Template:L/php/native | |
| dynamic property | $name | string | (Template:L/php/native) | |
| dynamic property | $value | int or string | (Template:L/php/native) | the name of the case (caps are preserved) |
Documentation
Note that enums can be cast directly to arrays.
- Enumerations:
- Classoids:
3rd party
Sample Code
To get a UnitEnum enum from a case name (equivalent to from()/tryFrom()):
- constant("Template:Arg::{$value}")
Tests
- is an
enuman object (is_object)? [YES] - is an
enumseen asis_a UnitEnum? [YES] - is an
enumaninstanceof UnitEnum? [YES] - is an
enumaninstanceof enum? [no]
