As any PHP developer knows, there is no native enum
support in PHP due to the fact that PHP is a dynamic language where a variable can be anything and everything. Many have tried to implement their own version of enum
support, some solutions working better than others. Here, I’ll give you my version of enum
support. If you like this approach, or if you prefer any other one, it is basically a matter of taste.
An Abstract Enum Template Class
The basic idea behind the enum
support is an abstract enum
class with the simple functionality we want the enum
to have. It includes type checking where you can check if a variable is of a certain enum
type and also the possibility to verify that only allowed enum
values are being used.
This is the code for the abstract
class:
abstract class Enum {
protected $value;
public function getValue()
{
return $this->value;
}
public function setValue($value)
{
if ($this->isValidEnumValue($value))
$this->value = $value;
else
throw new Exception("Invalid type specified!");
}
public function isValidEnumValue($checkValue)
{
$reflector = new ReflectionClass(get_class($this));
foreach ($reflector->getConstants() as $validValue)
{
if ($validValue == $checkValue) return true;
}
return false;
}
function __construct($value)
{
$this->setValue($value);
}
function __get($property)
{
return $this->value;
}
function __set($property, $value)
{
$this->setValue($value);
}
function __toString()
{
return (string)$this->value;
}
}
How to Create Your Own Enum
To create your own enum
using this abstract
class, simply do in the following way:
class MyEnum extends Enum {
const TypeA = "1";
const TypeB = "2";
const TypeC = "3";
}
The only thing your class should contain is constants with the values of your enum
. Why the integers are written as string
s is explained further down. It’s not mandatory, but it brings some extra possibilities.
To use the new enum
in code, simply write in the following way:
$myType = new MyEnum(MyEnum::TypeB);
$myType->setValue(MyEnum::TypeC);
if ($myType == MyEnum::TypeC) {
}
if ($myType instanceof MyEnum) {
}
function myFunction(MyEnum $myType)
{
}
Notes on the Abstract Enum Class
The code for the abstract enum
class is quite straight forward, but there are a few things I would like to highlight:
Limitations Using This Type of Enum
When you use enum
s in a language having it built in, you also have an “enum
understanding” in each and every enum
value. That’s not the case here where each value is a string
(or int
). You therefore have to take a little longer way to set an enum
, as illustrated here:
$myType = new MyEnum(MyEnum::TypeA);
$myType = new MyEnum(MyEnum::TypeC);
$myType->setValue(MyEnum::TypeA);
$myType = MyEnum::TypeA;
If you can live with that, you might have found a decent enum
implementation in PHP.
More Reading
If you want to read some more about the different PHP techniques used in this solution, you can continue here:
And here are some links to other people’s suggestions on enum
support in PHP: