PHP Sucks 0

Dec. 17, 2020

Note : This is a little series I will call PHP sucks. I used to rant about why PHP sucks in my day to day job to my friends, now I could just turn it into a series.

Enums

Enums are a special type that represents a group of constants.

They are useful for a lot of things, for example logging levels, or representing types of products available and so on. They biggest thing they do is bring type safety to bunch of constants.

Example in Java

enum EnumClass {
    FOO,
    BAR
}

If you try to use other value then Foo or Bar, it will thrown an exception.

The problem

They don’t exist in PHP. So if I have some need for enums the best way how I could do that is by creating a Class with public constants.


class EnumClass {
    public const FOO = 'foo';
    public const BAR = 'bar';
}

The thing is that if I ever want to use these enums, there are few problems

switch ($value) {
    case EnumClass::FOO:
        $this->doThing();
        break;
    case EnumClass::BAR:
        $this->doOtherThing();
        break;
    default: 
        throw new Exception('invalid value');
}

But this has a problem. What if someone, somewhere changed the case for the value and $value becomes FOO not foo? Now we gotta use some dumb thing like

switch (mb_strtolower($value)) {
    case EnumClass::FOO:
        $this->doThing();
        break;
    case EnumClass::BAR:
        $this->doOtherThing();
        break;
    default: 
        throw new Exception('invalid value');
}

This will work now, but that is a lot of bullshit to do. With proper types this would just thrown an error and I don’t have to worry about edge cases.

enum EnumClass {
    FOO,
    BAR
}

switch (value) {
    case FOO:
        this.doThing()
        break;
    case BAR:
        this.doOtherThing()
        break;
}

In other words I don’t like PHPs lack of proper enums and weak type system.