What is the usage of enums in PHP?

In PHP, there is no built-in enum type, but you can simulate its functionality by defining constants. Using constants to represent enum values can make the code easier to read and maintain.

Here is an example code for simulating an enumeration type:

abstract class Fruit {
    const APPLE = 1;
    const BANANA = 2;
    const ORANGE = 3;
}

$fruit = Fruit::APPLE;

switch ($fruit) {
    case Fruit::APPLE:
        echo "Selected fruit is Apple";
        break;
    case Fruit::BANANA:
        echo "Selected fruit is Banana";
        break;
    case Fruit::ORANGE:
        echo "Selected fruit is Orange";
        break;
    default:
        echo "Selected fruit is not recognized";
}

In this example, we have defined an abstract class “Fruit” and included several constants within the class to represent different types of fruit. We can then use these constants to indicate different fruit types and perform different operations based on the different enumerated values.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds