
Enumerations in PHP
Have you often regretted that PHP has no enumerations per se?
Yes, someone circumvented the naming convention and it turned out something like:
Or something like:
But both approaches have significant drawbacks:
Under the cut, I propose a solution without the above drawbacks ...
This is the base class for enumerations. When working, we only need to connect it and in the future we can forget about it.
Well, in order to implement the enumerations themselves, we need to write a similar structure:
And now to access the constant value and use type hinting we need to create an object from this class, passing the name of the necessary constant to the constructor:
Z.Y. But when the release of PHP5.3 comes out, it will be possible to add a method to the Enum class: which will return all pairs: the key-value is the original
Yes, someone circumvented the naming convention and it turned out something like:
define ('COLOR_RED', 'F00'); define ('COLOR_GREEN', '0F0'); define ('COLOR_BLUE', '00F');
Or something like:
// this variable is FORBIDDEN to modify $ colors = array ( 'red' => 'F00', 'green' => '0F0', 'blue' => '00F', );
But both approaches have significant drawbacks:
- In the first case, the members of the enumeration do not form an explicit grouping
- In the second case, there is a risk that the variable will be changed
- And in both of these cases, we can’t check for the type of the variable (type hinting)
Under the cut, I propose a solution without the above drawbacks ...
abstract class Enum { private $ current_val; final public function __construct ($ type) { $ class_name = get_class ($ this); $ type = strtoupper ($ type); if (constant ("{$ class_name} :: {$ type}") === NULL) { throw new Enum_Exception ('Properties'. $ type. 'in enumeration'. $ class_name. 'not found.'); } $ this-> current_val = constant ("{$ class_name} :: {$ type}"); } final public function __toString () { return $ this-> current_val; } } class Enum_Exception extends Exception {}
This is the base class for enumerations. When working, we only need to connect it and in the future we can forget about it.
Well, in order to implement the enumerations themselves, we need to write a similar structure:
class Enum_Colors extends Enum { const RED = 'F00'; const GREEN = '0F0'; const BLUE = '00F'; }
And now to access the constant value and use type hinting we need to create an object from this class, passing the name of the necessary constant to the constructor:
function setColor (Enum_Colors $ color) { echo $ color; } setColor (new Enum_Colors ('GREEN')); // will pass setColor ('0F0'); // won't pass Enum_Colors :: RED == new Enum_Colors ('GREEN'); // FALSE Enum_Colors :: RED == new Enum_Colors ('RED'); // TRUE
Z.Y. But when the release of PHP5.3 comes out, it will be possible to add a method to the Enum class: which will return all pairs: the key-value is the original
public static method asArray() {}