PHP中完美的枚举类型

9 浏览
0 Comments

PHP中完美的枚举类型

这个问题已经有了答案:

PHP中的枚举

最近我想到了在php中使用enums的解决方案:

    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提示,我可以遍历我所有的enums,但我认为我错过了一些可能有用的枚举特性。所以我的问题是:我可以添加哪些功能来更好地利用enums或使其更实用?

admin 更改状态以发布 2023年5月24日
0
0 Comments

我认为您也可以实现ArrayAccess和Countable

 class Enum implements ArrayAccess, Countable, Iterator {

0