phpenumsphp-8.1

Variable key on php enum


Is it possible to access enumerations properties dynamically?

Here is what I tried and the error I got.

Access to undeclared static property ExampleEnum::$id

enum ExampleEnum
{
    case _1;
    case _2;

    public function getIt(): string
    {
        return match ($this) {
            ExampleEnum::_1 => 'foo',
            ExampleEnum::_2 => 'bar',
        };
    }
}

$id = "_1";
ExampleEnum::$id->getIt();

Solution

  • It's important to distinguish between three different things here:

    In fact, an enum case is treated like a constant in many ways, and a test shows that both the constant function and the PHP 8.3 dynamic constant syntax can be used to look one up, so this will work:

    enum ExampleEnum
    {
        case _1;
        case _2;
    
        public function getIt(): string
        {
            return match ($this) {
                ExampleEnum::_1 => 'foo',
                ExampleEnum::_2 => 'bar',
            };
        }
    }
    
    $id = "_1";
    
    // PHP 8.3 or later only:
    echo ExampleEnum::{$id}->getIt();
    
    // any version supporting enums (PHP 8.0 or later):
    echo constant("ExampleEnum::$id")->getIt();
    

    Note that if you use a "backed enumeration", you can associate an arbitrary integer or string with each case, separate from its name, and use the from method to look up a case based on that value.