Creating a fake enum in PHP.

In a current project I needed to solve a problem where I wanted a class to only accept a set list of string values in a setter. In other languages you could use an enum to easily solve this. Unfortunately, PHP does not have anything like an enum natively. I needed to come up with a solution myself. I had two requirements:

  1. Limit input to a set list of strings
  2. Code completion of the values

Doing some research there were a number of developers looking for something like a enum and just as many solutions.

I ended up combining a few tricks I saw from my research. I wrote an abstract class with constants named and set to the strings I wanted to limit input to. Then I wrote a static method that checks if a string is a valid member of the class by seeing if there is a constant defined with that name.

Here’s a simplified version of the class:

Now I could setup my setter on the other class like this:

public function setSomething($value)
{
    if (FakeEnum::isValid($value)) {
        $this->something = $value;
    }
}

Then call the setter like this:

$myClass->setSomething(FakeEnum::value_one);

Typing FakeEnum:: in my IDE would use auto-completion to pull up a list of all the constants in the FakeEnum class.

Leave a Reply