Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class PageSpecial extends AEnum
- {
- static final function home()
- {
- return self::get();
- }
- static final function conditions()
- {
- return self::get();
- }
- }
- class Month extends AEnum
- {
- static final function JANUARY()
- {
- return self::get(1);
- }
- static final function FEBRUARY()
- {
- return self::get(2);
- }
- }
- class Color extends AEnum
- {
- private $r, $g, $b;
- protected function init($r, $g, $b)
- {
- $this->r = $r;
- $this->g = $g;
- $this->b = $b;
- }
- static final function BLACK()
- {
- return self::get(0, 0, 0);
- }
- static final function WHITE()
- {
- return self::get(255, 255, 255);
- }
- }
- function linkPage(PageSpecial $special) {
- echo $special;
- }
- echo Month::FEBRUARY();
- linkPage(PageSpecial::CONDITIONS());
- $feb = Month::FEBRUARY();
- var_dump($feb === Month::FEBRUARY());
- var_dump($feb() + 1);
- var_dump(Color::WHITE());
- var_dump(Color::getNames());
- //----------------------------------------
- abstract class AEnum
- {
- private static $instances, $initialized, $names;
- private $value;
- private function __construct($value)
- {
- $class = get_called_class();
- if (empty(self::$initialized[$class])) {
- self::$initialized[$class] = true;
- if (is_callable('static::init')) {
- $m = new \ReflectionMethod($class, 'init');
- if (!$m->isProtected()) {
- trigger_error(
- "Method init in class $class must be protected",
- E_USER_ERROR
- );
- }
- }
- static::saveNames();
- }
- $this->value = (string) $value;
- }
- function __toString()
- {
- return (string) $this->value;
- }
- function __invoke()
- {
- return $this->value;
- }
- static final function getNames()
- {
- static::saveNames();
- return self::$names[get_called_class()];
- }
- protected static final function get()
- {
- $class = get_called_class();
- $name = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'];
- if (empty(self::$instances[$class][$name])) {
- self::$instances[$class][$name] = new $class(
- func_num_args() == 1 ? func_get_arg(0) : $name
- );
- }
- $enum = self::$instances[$class][$name];
- if (is_callable("static::init")) {
- if (func_num_args()) {
- call_user_func_array(
- array($enum, 'init'), func_get_args()
- );
- } else {
- $enum->init();
- }
- }
- return $enum;
- }
- private final static function saveNames()
- {
- $class = get_called_class();
- if (!isset(self::$names[$class])) {
- $c = new \ReflectionClass($class);
- self::$names[$class] = array();
- foreach ($c->getMethods() as $m) {
- if ($m->isFinal() && $m->isStatic() &&
- $m->getDeclaringClass() == $c
- ) {
- self::$names[$class][] = strtoupper($m->getName());
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement