gpt4 book ai didi

php - PHP 中的完美枚举

转载 作者:搜寻专家 更新时间:2023-10-31 21:18:09 24 4
gpt4 key购买 nike

<分区>

最近我想出了这个用于 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 提示,我可以遍历我所有的枚举,但我想我错过了一些可能有用的枚举功能。所以我的问题是:我可以添加哪些功能来更多地使用枚举或使其更实用?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com