Advertisement
Guest User

PHP enumerated string value

a guest
Jul 17th, 2011
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.73 KB | None | 0 0
  1. class PageSpecial extends AStringEnum
  2. {
  3.     static final function conditions()
  4.     {
  5.         return self::get(__FUNCTION__);
  6.     }
  7.    
  8.     static final function home()
  9.     {
  10.         return self::get(__FUNCTION__);
  11.     }
  12.  
  13.     static final function HOMEPAGE()
  14.     {
  15.         return self::home();
  16.     }
  17.  
  18.     static final function DOMOV()
  19.     {
  20.         return self::get('home');
  21.     }
  22. }
  23.  
  24. abstract class AStringEnum
  25. {
  26.     private static $instances, $list;
  27.     private $value;
  28.  
  29.     private function __construct($value)
  30.     {
  31.         $this->value = (string) $value;
  32.     }
  33.  
  34.     final function __toString()
  35.     {
  36.         return $this->value;
  37.     }
  38.    
  39.     static final function getList()
  40.     {
  41.         if (is_null(self::$list)) {
  42.             $class = get_called_class();
  43.             $c = new \ReflectionClass($class);
  44.             self::$list = array();
  45.            
  46.             foreach ($c->getMethods() as $m) {
  47.                 $name = strtoupper($m->getName());
  48.  
  49.                 if ($m->isFinal() && $m->isStatic() && !in_array($name, array(
  50.                     'GET', 'GETLIST'
  51.                 ))) {
  52.                     self::$list[$name] = (string) $class::$name();
  53.                 }
  54.             }
  55.         }
  56.        
  57.         return self::$list;
  58.     }
  59.  
  60.     protected static final function get($value)
  61.     {
  62.         $value = (string) $value;
  63.  
  64.         if (empty(self::$instances[$value])) {
  65.             $class = get_called_class();
  66.             self::$instances[$value] = new $class($value);
  67.         }
  68.  
  69.         return self::$instances[$value];
  70.     }
  71. }
  72.  
  73. var_dump(
  74.     PageSpecial::HOME() === PageSpecial::HOMEPAGE() &&
  75.     PageSpecial::HOMEPAGE() === PageSpecial::DOMOV()
  76. );
  77. print_r(PageSpecial::getList());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement