How to add enumerations in PHP?

Spread the love

Sometimes, we want to add enumerations in PHP.

In this article, we’ll look at how to add enumerations in PHP.

How to add enumerations in PHP?

To add enumerations in PHP, we can add enums with PHP 8.1 or later or use classes otherwise.

For instance, we write

enum TransportMode
{
    case Bicycle;
    case Car;
    case Ship;
    case Plane;
    case Feet;
}

to add a native enum.

Or we can write

class EnumClass
{
    const NAME = "aaaa";
    const SOME_VALUE = "bbbb";
}

print EnumClass::NAME;

to add the EnumClass class with some static values.

Then we can get a value from it with EnumClass::NAME.

Conclusion

To add enumerations in PHP, we can add enums with PHP 8.1 or later or use classes otherwise.

Leave a Reply

Your email address will not be published.