3

Recently i came up with this solution for enums in php:

    class Enum implements Iterator {
        private $vars = array();
        private $keys = array();
        private $currentPosition = 0;

        public function __construct() {
        }

        public function current() {
            return $this->vars[$this->keys[$this->currentPosition]];
        }

        public function key() {
            return $this->keys[$this->currentPosition];
        }

        public function next() {
            $this->currentPosition++;
        }

        public function rewind() {
            $this->currentPosition = 0;
            $reflection = new ReflectionClass(get_class($this));
            $this->vars = $reflection->getConstants();
            $this->keys = array_keys($this->vars);
        }

        public function valid() {
            return $this->currentPosition < count($this->vars);
        }

}

Example:

class ApplicationMode extends Enum
{
    const production = 'production';
    const development = 'development';
}

class Application {
    public static function Run(ApplicationMode $mode) {
        if ($mode == ApplicationMode::production) {
        //run application in production mode
        }
        elseif ($mode == ApplicationMode::development) {
            //run application in development mode
        }
    }
}

Application::Run(ApplicationMode::production);
foreach (new ApplicationMode as $mode) {
    Application::Run($mode);
}

it works just perfect, i got IDE hints, i can iterate through all my enums but i think i miss some enums features that can be useful. so my question is: what features can i add to make more use of enums or to make it more practical to use?

  • 5
    *(official)* [Request for Comments: Enum](http://wiki.php.net/rfc/enum) and also [SplEnum](http://de2.php.net/manual/en/class.splenum.php) – Gordon Oct 07 '10 at 11:32

1 Answers1

2

I think you can olso implement ArrayAccess and Countable

 class Enum implements ArrayAccess, Countable, Iterator {
keepwalking
  • 2,644
  • 6
  • 28
  • 63