[Coding] PHP Enum

Today I was looking for a way to build an Enum in PHP. To my surprise, this is not really supported (yet). There is ‘SplEnum’. But this object is apparently ‘experimental’. So after some looking around, here is a way of creating an Enum (like) object in PHP:

class {
    private $value = ::;

    const  = ;
    const  = ;
    enz...

    //Get the correct constant name related to the given input value ($i)
    public function ($i){
        $reflectionObj = new ReflectionObject($this);
        //Loop trough constants to find the right value
        foreach( $reflectionObj->getConstants() as $constant=>value ){
            if($value == $i){
                $this->value = $constant;
                return constant("::".$constant)
            }
        throw new Exception("Value (" . $i . ") not found in ");
    }

    //Just making sure the object is printed correctly when asked for
    public function __tostring(){ return $this->value; }
}

Of course there are multiple way’s of building an Enum ‘like’ structure with associated array’s or DEFINE(‘’) But lets be honest, this is way cooler!

Unfortunately I haven’t found a way yet of making it a Class you can inherit from because you’ll have to do a trick with the super function (parent::functionName()). And those don’t work most of the time (if it comes to usability of your object).

Do you know a better way? Please do let me know because I think this is really a feature that is missing in the current PHP release.

Cheers, Ruben.

Comments