Appearance
Enumerations on PHP
In PHP, an enumeration is a type that restricts a variable to a fixed set of values. This can be useful when you want to limit the possible values that a variable can take on.
To create an enumeration in PHP, you can use the enum keyword. For example:
Example of Enumeration in PHP
php
enum Days: int {
case MONDAY = 1;
case TUESDAY = 2;
case WEDNESDAY = 3;
case THURSDAY = 4;
case FRIDAY = 5;
case SATURDAY = 6;
case SUNDAY = 7;
}You can then use these enum cases like any other value. Native enums provide type safety and can include additional methods or properties if needed.
For example:
Example of using an Enumeration in PHP
php
<?php
enum Days: int {
case MONDAY = 1;
case TUESDAY = 2;
case WEDNESDAY = 3;
case THURSDAY = 4;
case FRIDAY = 5;
case SATURDAY = 6;
case SUNDAY = 7;
}
$day = Days::MONDAY;
echo $day->value . PHP_EOL; // Outputs 1
$day = Days::TUESDAY;
echo $day->value; // Outputs 2
// Native enums enforce type safety. Assigning a raw integer directly is allowed,
// but converting it to an enum case requires explicit validation:
$day = Days::from(10); // Throws ValueError: "10" is not a valid backing valueThis approach allows you to use the enum cases in a more intuitive way, as you can access their values using the ->value property. It also allows you to define additional methods or properties in the enum, if needed.