I know that PHP doesn't have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values which IDEs' auto completion features could understand.
Constants do the trick, but there's the namespace collision problem and (or actually because) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely (never?) know how to autofill their keys.
Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enums?
What about class constants?
I use
interface
instead ofclass
:If you need to use enums that are globally unique (i.e. even when comparing elements between different Enums) and are easy to use, feel free to use the following code. I also added some methods that I find useful. You will find examples in the comments at the very top of the code.
Yesterday I wrote this class on my blog. I think it's maybe be easy for use in php scripts:
Usage:
I found this library on github and I think it provides a very decent alternative to the answers here.
PHP Enum implementation inspired from SplEnum
function setAction(Action $action) {
format
,parse
, …)final
to prevent it)Declaration
Usage
type-hint enum values:
I've commented on some of the other answers here, so I figured I would weigh in too. At the end of the day, since PHP doesn't support typed enumerations, you can go one of two ways: hack out typed enumerations, or live with the fact that they're extremely difficult to hack out effectively.
I prefer to live with the fact, and instead use the
const
method that other answers here have used in some way or another:An example enumeration:
Using
Enum
as a base class from which all other enumerations extend allows for helper methods, such astoArray
,isValid
, and so on. To me, typed enumerations (and managing their instances) just end up too messy.Hypothetical
If, there existed a
__getStatic
magic method (and preferably an__equals
magic method too) much of this could be mitigated with a sort of multiton pattern.(The following is hypothetical; it won't work, though perhaps one day it will)