使用PHP简单粗暴的模枚举
class State
{
const EnumState = [
'SMALL' => 0,
'SUPER' => 1 ,
'FIRE' => 2 ,
'CAPE' => 3
];
private $value;
public function __construct()
{
if(count(array_unique(array_values(self::EnumState))) != count(self::EnumState))
{
throw new \Exception('Key value is not unique!');
}
$this->value = self::EnumState['SMALL'];
}
public function getValue(){
return array_search($this->value,self::EnumState);
}
public function setValue($value){
if( !in_array($value,array_keys(self::EnumState))) {
throw new \Exception('Don\'t in this state!');
}
$this->value = self::EnumState[$value];
}
}
$obj = new \App\State();
echo $obj->getValue().PHP_EOL;
$obj->setValue('CAPE');
echo $obj->getValue().PHP_EOL;
运行结果如图
参考: [1] https://www.php.net/manual/zh/ref.array.php
|