📜 ⬆️ ⬇️

PHP Enumerations

How often have you regretted that PHP has no enums per se?

Yes, someone got along with 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:


Under the cut offer a solution without the above disadvantages ...

 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 the 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 enums. When working, we will 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 refer to a 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


ZY But when PHP5.3 release comes out, you can add a method to the Enum class:
public static method asArray() {}

which will return all pairs: key-value
original

Source: https://habr.com/ru/post/38584/


All Articles