Advertisement
MrLore

PHP: Fake Enums with validation

Nov 11th, 2012
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.15 KB | None | 0 0
  1. /**
  2.  * PHP: Fake Enums with validation method.
  3.  * @author MrLore <[email protected]>
  4.  */
  5.  
  6. final class FakeEnums
  7. {
  8.     const ENUM_ONE = 'one';
  9.     const ENUM_TWO = 'two';
  10.     const ENUM_THREE = 'three';
  11.    
  12.     private static $validConstants;
  13.    
  14.     private function __construct(){ /* Enum: Instantiation not allowed. */}
  15.    
  16.     /**
  17.      * Returns true if the specified type is an emum of this class
  18.      *
  19.      * @param mixed $type The value to compare to this class' constants.
  20.      * @return boolean True if $type is a constant of this class.
  21.      */
  22.     public static function isValid($type)
  23.     {
  24.         return in_array($type, (isset(self::$validConstants) ? self::$validConstants : (self::$validConstants = _rv(new ReflectionClass(__CLASS__))->getConstants())));
  25.     }//End isValid()
  26. }//End FakeEnums
  27.  
  28. /**
  29.  * Allows chaining of methods from their declaration.
  30.  *
  31.  * e.g:
  32.  *
  33.  * new ReflectionClass(__CLASS__)->getConstants();
  34.  *  Produces: syntax error, unexpected '->' (T_OBJECT_OPERATOR)
  35.  *
  36.  * _rv(new ReflectionClass(__CLASS__))->getConstants();
  37.  *  Works fine.
  38.  */
  39. function _rv($val)
  40. {
  41.     return $val;
  42. }//End _rv()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement