<?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)容
雅