Looking for native enumeration with PHP? Sadly you are out of luck. PHP simply does not support enumeration out of the box. Fortunately though you do have some options. Each one has its attributes and shortcomings based upon your needs.
- splEnum: This is an experimental PHP extension that will provide enumeration that’s as close to native support as you’re going to get. Because it requires installing additional files to work, it is not a good solution unless you have full server control. Personally I avoid this approach at all costs. I prefer clean installs of PHP. Also, depending on extensions makes your code non portable.
- Custom class: There are a lot of great enumeration classes out there, or you could always write one from scratch. Marijan Šuflaj has written an excellent version available for use here. The primary disadvantage is complexity. Even using a pre-made class the instantiation and function calls are sometimes just not worth it when all you need is a straight forward list of enumerated values.
- The third option: Leverage abstract classes to create an encapsulated list. This is the simplest route and what I shall be demonstrating here.
Creating a value list really is a simple affair with PHP. All you need is to craft an abstract class and define a group of constants within it. Abstract classes cannot be instantiated as objects, but their members are immediately available for referencing.
Here is an example for calendar months.
// Set up a list of months. abstract class MONTH { const JANUARY = 1, FEBRUARY = 2, MARCH = 3, APRIL = 4, MAY = 5, JUNE = 6, JULY = 7, AUGUST = 8, SEPTEMBER = 9, OCTOBER = 10, NOVEMBER = 11, DECEMBER = 12; } // Now echo a value. echo MONTH::APRIL;
That’s really all there is to it! Sure, this isn’t true enumeration. You must still key in values. Plus there’s no error checking or type hinting for switch operations and similar ilk as you’d find in a compiled language. What you do get is a simple list with encapsulation and list type hinting from the IDE. All with minimal code. Keeping the global namespace clean alone is a fantastic benefit.
For most rudimentary enumeration needs this should prove more than sufficient, at least until the fine folks at PHP step up and provide us with the real thing.
Until next time!
DC