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.
Example. This program specifies a Color enum with 3 possible cases: Orange, Magenta and Fuchsia. It is a little different than most Color enums.
Step 1 We assign the color variable "c" in our PHP program to the Orange case of the enum.
Step 2 We test the enum local variable with an if-statement. The test succeeds, as the enum is the Orange color.
Step 3 It is possible to use a match statement on an enum—this can lead to clearer, more compact code that is easier to maintain.
Step 4 The name property returns a string representation of the enum case. We can manipulate it like any other string.
enumColor {
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
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.