PHP 使用反射获取常量名、值及注释
基类代码如下:
<?php
namespace app\common\enums;
use ReflectionClassConstant;
class BaseEnum
{
public static function getConst(): array
{
$objClass = new \ReflectionClass(get_called_class());
return $objClass->getConstants();
}
public static function getConstantsKeys(): array
{
return array_keys(self::getConst());
}
public static function getConstantsValues(): array
{
return array_values(self::getConst());
}
public static function getDescription(string $key): string
{
return preg_replace('#[\*\s]*(^/|/$)[\*\s]*#', '', (new ReflectionClassConstant(static::class, $key))->getDocComment());
}
public static function getKeyDescription(): array
{
$keys = self::getConstantsKeys();
$result = [];
foreach ($keys as $key => $key_name) {
$result[$key_name] = self::getDescription($key_name);
}
return $result;
}
public static function getValueDescription(): array
{
$const = self::getConst();
$result = [];
foreach ($const as $key => $value) {
$result[$value] = self::getDescription($key);
}
return $result;
}
}
子类代码如下:
<?php
namespace app\common\enums;
class PacketStatus extends BaseEnum
{
const UNCLAIMED = 0;
const READY = 1;
const PROCESSING = 2;
const SUCCESS = 3;
const FAIL = 4;
}
如何使用
获取所有常量
PacketStatus::getConst()
array(5) {
["UNCLAIMED"] => int(0)
["READY"] => int(1)
["PROCESSING"] => int(2)
["SUCCESS"] => int(3)
["FAIL"] => int(4)
}
获取所有常量名
PacketStatus::getConstantsKeys()
array(5) {
[0] => string(9) "UNCLAIMED"
[1] => string(5) "READY"
[2] => string(10) "PROCESSING"
[3] => string(7) "SUCCESS"
[4] => string(4) "FAIL"
}
获取所有常量值
PacketStatus::getConstantsValues()
array(5) {
[0] => int(0)
[1] => int(1)
[2] => int(2)
[3] => int(3)
[4] => int(4)
}
获取常量名和注释列表
PacketStatus::getKeyDescription()
array(5) {
["UNCLAIMED"] => string(9) "未领取"
["READY"] => string(9) "未发放"
["PROCESSING"] => string(9) "处理中"
["SUCCESS"] => string(12) "发放成功"
["FAIL"] => string(12) "发放失败"
}
获取常量值和注释列表
PacketStatus::getValueDescription()
array(5) {
[0] => string(9) "未领取"
[1] => string(9) "未发放"
[2] => string(9) "处理中"
[3] => string(12) "发放成功"
[4] => string(12) "发放失败"
}