Home
Map
enum Examples (case)Use an enum to store a group of related constants and handle them in a consistent way.
PHP
This page was last reviewed on Jul 10, 2023.
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.
if, elseif
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.
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
Backed 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.
Here We specify that the Priority enum is backed by ints. We use the values 100, 50 and 0 for the backing ints.
Next We invoke the 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.
C#VB.NETPythonGoJavaSwiftRust
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.
This page was last updated on Jul 10, 2023 (image).
Home
Changes
© 2007-2023 Sam Allen.