PHP中的完美枚举[重复]
Posted
技术标签:
【中文标题】PHP中的完美枚举[重复]【英文标题】:Perfect Enums in PHP [duplicate] 【发布时间】:2011-04-22 07:44:33 【问题描述】:最近我想出了这个 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 提示,我可以遍历我所有的枚举,但我想我错过了一些有用的枚举功能。 所以我的问题是:我可以添加哪些功能来更多地使用枚举或使其更实用?
【问题讨论】:
(官方) Request for Comments: Enum 和 SplEnum 【参考方案1】:我认为你也可以实现 ArrayAccess 和 Countable
class Enum implements ArrayAccess, Countable, Iterator
【讨论】:
以上是关于PHP中的完美枚举[重复]的主要内容,如果未能解决你的问题,请参考以下文章