PHP中如何定义枚举

2019-07-03  本文已影响0人  webxiaohua

在系统开发中无法避免需要引入许多标志字段,如果是直接硬编码进代码中会造成后期的难以维护,因此我们引入java中的枚举类型,方便解读标志字段

class GenderEnum
{
    const MALE = array('code'=>1,'desc'=>'男');
    const FEMALE = array('code'=>2,'desc'=>'女');
    private static $kvCodeDesc = [
        GenderEnum::MALE['code']=>GenderEnum::MALE['desc'],
        GenderEnum::FEMALE['code']=>GenderEnum::FEMALE['desc']
    ];
    public static function getCodeDesc($code){
        if(isset(self::$kvCodeDesc[$code])){
            return self::$kvCodeDesc[$code];
        }else{
            return "未知";
        }
    }
    public static function getAll(){
        $list = [];
        foreach(self::$kvCodeDesc as $k=>$v){
            $list[] = array('code'=>$k,'desc'=>$v);
        }
        return $list;
    }
}

使用方式:

if($user['gender'] == GenderEnum.MALE['code']){
  // do something
}
$user['gender'] = GenderEnum.FEMALE['code'];

这样代码的可读性更高了对吗?

上一篇下一篇

猜你喜欢

热点阅读