Enum
Often in PHP programs we have many related constants. For example, a color may be any value from the rainbow—these are ideally stored in an enum
.
With some helpful properties, we can access information about the enum
cases. The name property will return a string
representation of the enum
.
This program specifies a Color enum
with 3 possible cases: Orange, Magenta and Fuchsia. It is a little different than most Color enums.
enum
.enum
local variable with an if
-statement. The test succeeds, as the enum
is the Orange color.enum
—this can lead to clearer, more compact code that is easier to maintain.string
representation of the enum
case. We can manipulate it like any other string
.enum Color { case Orange; case Magenta; case Fuchsia; } // Step 1: assign local variable to enum value. $c = Color::Orange; // Step 2: test enum value with if. if ($c == Color::Orange) { var_dump($c); } // Step 3: use another enum value and then match it. $c = Color::Magenta; $result = match ($c) { Color::Orange => "o", Color::Magenta => "m", Color::Fuchsia => "f" }; echo $result, "\n"; // Step 4: convert enum to string with name. $name = $c->name; $name_upper = strtoupper($name); echo "{$name} {$name_upper}\n";enum(Color::Orange) m Magenta MAGENTA
enum
It is sometimes useful to associate a value with each enum
case. For example, a priority enum
could have an integer indicating the importance of each case.
enum
is backed by ints. We use the values 100, 50 and 0 for the backing ints.cases()
function to get all the cases. We can then loop over the cases and print their names and values.// Int-backed enum. enum Priority: int { case Top = 100; case Medium = 50; case Bottom = 0; } // Get cases. $cases = Priority::cases(); var_dump($cases); // Loop over cases. foreach (Priority::cases() as $c) { echo "Name = " . $c->name . ", Value = " . $c->value . "\n"; }
Programs written in PHP can use constants and even locals to designate possible values—enums are not required. But enums are helpful—they organize the possible cases in one place.