How to create an enumeration of constants with and without explicit values in PHP

1 Answer

0 votes
/* 
   Title: Enumeration of Constants in PHP
   Example with and without explicit values 
*/

// -------------------------------
// Enum WITHOUT explicit values
// PHP automatically assigns no numeric values,
// but you can still use them as named constants.
// -------------------------------
enum Color {
    case Red;     // ordinal-like position 0
    case Green;   // 1
    case Blue;    // 2
}

// -------------------------------
// Enum WITH explicit values
// Backed enums allow assigning string or int values.
// -------------------------------
enum Status: int {
    case OK = 1;
    case Warning = 5;
    case Error = 6;
    case Critical = 10;
}

echo "Enum without explicit values:\n";
echo "Red = " . Color::Red->name . "\n";
echo "Green = " . Color::Green->name . "\n";
echo "Blue = " . Color::Blue->name . "\n";

echo "\nEnum with explicit values:\n";
echo "OK = " . Status::OK->value . "\n";
echo "Warning = " . Status::Warning->value . "\n";
echo "Error = " . Status::Error->value . "\n";
echo "Critical = " . Status::Critical->value . "\n";


/* 
run:

Enum without explicit values:
Red = Red
Green = Green
Blue = Blue

Enum with explicit values:
OK = 1
Warning = 5
Error = 6
Critical = 10

*/

 



answered Apr 25 by avibootz

Related questions

...