phparraysenumsspl

How to convert php enum to array?


I've got the following enum:

abstract class DaysOfWeek
{
    const Sunday = 0;
    const Monday = 1;
    // etc.
}

How can I modify the following function to generate an array based on the enum above?

public function getOptions()
{
    return [
        0 => 'Sunday',
        1 => 'Monday',
    ];
}

Isn't it better to use SplEnum for this purpose?


Solution

  • I'm not sure if it's better to use Splenum, but I know this can be done using ReflectionClass. Assuming you want getOptions to be defined in a class that extends DaysOfWeek, your code might look something like this:

    abstract class DaysOfWeek
    {
        const Sunday = 0;
        const Monday = 1;
        // etc.
    }
    
    
    class myClass extends DaysOfWeek {
        public function getOptions() {
                $oClass = new ReflectionClass(__CLASS__);
                $constants = $oClass->getConstants();
                $retval = array();
                foreach($constants as $name => $val) {
                        $retval[$val] = $name;
                }
                return $retval;
        }
    }
    
    $o = new myClass();
    var_dump($o->getOptions());
    

    EDIT: here's an even more compact and efficient version of the getOptions function which uses native PHP functions:

        public function getOptions() {
                $oClass = new ReflectionClass(__CLASS__);
                $constants = $oClass->getConstants();
                return(array_combine(array_values($constants), array_keys($constants)));
        }
    

    EDIT 2: If getOptions is in a class that does NOT extend DaysOfWeek, you can simply refer to the classname like so:

    class AnotherClass {
        public function getOptions() {
                $oClass = new ReflectionClass(DaysOfWeek);
                $constants = $oClass->getConstants();
                return(array_combine(array_values($constants), array_keys($constants)));
        }
    }
    
    $o = new AnotherClass();
    var_dump($o->getOptions());