国产+高潮+在线,国产 av 仑乱内谢,www国产亚洲精品久久,51国产偷自视频区视频,成人午夜精品网站在线观看

分享一段關(guān)于常量的處理,主要解決平時很多狀態(tài)需要轉(zhuǎn)換為中文的問題

cncoder
  1. 在support目錄下新建一個 constant/BaseConstant.php文件,內(nèi)容如下:
<?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);
    }

    /**
     * 獲取所有值對應(yīng)的中文
     * @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;
    }
}

使用如下

比如我們有 用戶狀態(tài)為 0 = 待審核 1 正常 2凍結(jié)

那么我們可以創(chuàng)建一個UserStatus.php的文件用來存放用戶的狀態(tài),代碼如下:

<?php
namespace app\constant;

use support\constant\BaseConstant;

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

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

    /**
     * @message(凍結(jié))
     */
    const REJECT = 2;
}

那么我們可以這樣使用

    UserStatus::all(); //獲取所有常量
    UserStatus::get($name);//獲取某一個常量的值 
    UserStatus::messages(); 獲取一個類似于 [0 => '待審核', 1=>'正常', 2 => '凍結(jié)'] 的數(shù)組主要用于一些地方的篩選用
    UserStatus::message($value); 獲取指定值對應(yīng)的@message的內(nèi)容
748 3 4
3個評論

lanaz

  • 暫無評論
10bang

感謝分享

  • 暫無評論
xiaozhiyue

感謝分享

  • 暫無評論

cncoder

120
積分
0
獲贊數(shù)
0
粉絲數(shù)
2023-05-15 加入
??