Enums in PHP

Who knew enums could be so difficult in PHP 5.3?!? There are probably better options with higher versions of PHP, but I’m not to that point yet.

I tried to use the PHP provided SplEnum, but I could not get it to work with all of the default install of PHP. Maybe I had something wrong, or needed to enabled something in the php.ini file, but either way, enums should not be this hard.

[19-Jul-2015 15:15:33] PHP Fatal error: Class ‘SplEnum’ not found in C:\dev\php\workspace\project\StatusEnum.php on line 2

There are a few good options of enum classes that others have created out on the web, so instead of re-inventing the wheel, I borrowed one of the simpler enum implementations.

abstract class MyEnum
{
    final public function __construct($value)
    {
        $c = new ReflectionClass($this);
        if(!in_array($value, $c->getConstants())) {
            throw IllegalArgumentException();
        }
        $this->value = $value;
    }

    final public function __toString()
    {
        return $this->value;
    }
}

class Foo extends MyEnum
{
    const FOO = "foo";
    const BAR = "bar";
}

$a = new Foo(Foo::FOO);
$b = new Foo(Foo::BAR);
$c = new Foo(Foo::BAR);

if($a == Foo::FOO) {
    echo "My value is Foo::FOO\n";
} else {
    echo "I dont match!\n";
}

if($a == $b) {
    echo "a value equals b value!\n";
}
if($b == $c) {
    echo "b value equals c value!\n";
}

I think I may extend this to be a little more java-like (hasKey(), etc.), but for now, the most basic enum class above will work great for my needs.

About the Author

Sean

View Posts →

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.