分享一段关于常量的处理,主要解决平时很多状态需要转换为中文的问题

cncoder
  1. 在support目录下新建一个 constant/BaseConstant.php文件,内容如下:
<?php
namespace support\constant;

class BaseConstant
{
    /**
     * 获取所有的常量
     * @return array
     */
    public static function all()
    {
        $reflection = new \ReflectionClass(static::class);
        return $reflection->getConstants();
    }

    /**
     * 获取某个常量的值
     * @param $name
     * @return mixed|null
     */
    public static function get($name)
    {
        $reflection = new \ReflectionClass(static::class);
        return $reflection->getConstant($name);
    }

    /**
     * 获取所有值对应的中文
     * @return array
     */
    public static function messages()
    {
        $reflection = new \ReflectionClass(static::class);
        $constants = $reflection->getReflectionConstants();

        $messages = [];
        foreach ($constants as $key => $constant) {
            $doc = $constant->getDocComment();
            $pattern = '/@message\((.*?)\)/';
            if (preg_match($pattern, $doc, $matches)) {
                $messages[$constant->getValue()] = trim( $matches[1] );
            }
        }
        return $messages;
    }

    /**
     * 获取某个常量的值
     * @param $value
     * @return mixed|null
     */
    public static function message($value)
    {
        $messages = static::messages();
        return isset($messages[$value]) ? $messages[$value] : null;
    }
}

使用如下

比如我们有 用户状态为 0 = 待审核 1 正常 2冻结

那么我们可以创建一个UserStatus.php的文件用来存放用户的状态,代码如下:

<?php
namespace app\constant;

use support\constant\BaseConstant;

class UserStatus extends BaseConstant
{
    /**
     * @message(待审核)
     */
    const WAITING = 0;

    /**
     * @message(正常)
     */
    const APPROVE = 1;

    /**
     * @message(冻结)
     */
    const REJECT = 2;
}

那么我们可以这样使用

    UserStatus::all(); //获取所有常量
    UserStatus::get($name);//获取某一个常量的值 
    UserStatus::messages(); 获取一个类似于 [0 => '待审核', 1=>'正常', 2 => '冻结'] 的数组主要用于一些地方的筛选用
    UserStatus::message($value); 获取指定值对应的@message的内容
197 1 0
1个评论

卷心菜

实用,学到了!

  • 暂无评论

cncoder

120
积分
0
获赞数
0
粉丝数
2023-05-15 加入
×
🔝