完美的 PHP 枚举类型

3

最近我想出了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);
        }

}

例子:

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);
}

它运行得非常完美,我得到了IDE提示,我可以遍历所有的枚举,但我认为我错过了一些有用的枚举功能。所以我的问题是:我可以添加哪些功能来更好地利用枚举或使其更实用?


5
《请求评论:枚举》和《SplEnum》 这是两个关于 PHP 编程语言中枚举类型的文档。其中,《请求评论:枚举》是一个官方的 RFC(请求评论)文件,介绍了在 PHP 中引入枚举类型的设计和实现方式。而《SplEnum》则是 PHP 的标准库中提供的一个类,用于实现枚举类型。 - Gordon
1个回答

2
我认为你也可以实现ArrayAccess和Countable。
 class Enum implements ArrayAccess, Countable, Iterator {

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接