If you’re familiar with a language other than PHP, it’s likely that you’ve encountered native implementations of the enumeration data type. It’s a primitive that was present even back in the early days of Pascal, back in the ’80s. Don’t get me wrong, I’m a massive fan of PHP, but there are definitely times I wish enums were natively supported. After all, they’re so common in the real world that any reduction in implementation impedance as a developer would be fantastic.
And recently – I think my dream came true.
A recent requests for comments just passed the majority vote needed to proceed to the next phase.
Before we get excited, what do we currently do?
There are a few current options. Some developers opt for using class constants and simply statically reference them throughout their code. This is an okay solution, I guess. And while it’s better than string literals sprinkled everywhere, it’s not exactly going to win any awards for design.
A better alternative is to somehow hijack PHP’s existing type system and get all the sweet, sweet benefits of type safety. At least this way, passing a constant from another class will cause your code to break at design time rather than run time. It’s also an interesting use-case for a protected constructor, which is a reasonably rare encounter.
Of course, you don’t have to code this yourself. Many of us have ended up at this destination and some kind souls have developed libraries around this very idea. Here’s one such library. And another. And another.
The future
The RFC itself introduces a new language construct, enum. It’s a first-class citizen, like classes and interfaces and will support standard-compliant autoloading. This means we will be able to use them in type hinting statements. Yay!
This is the proposed syntax:
But the RFC has gone further and allowed for backed enums, essentially meaning each enumeration option can be serialized into a primitive type, which will be incredibly important if we want to streamline the movement of an instance to and from a database.
A backed enum of the above example would look as follows:
The RFC passed the vote, 44 in support, 7 against. I for one cannot wait to see how this progresses.
Photo by Clay Banks on Unsplash