Den*_*ovs 49 php class constants
假设你在类中定义了一个常量:
class Foo {
const ERR_SOME_CONST = 6001;
function bar() {
$x = 6001;
// need to get 'ERR_SOME_CONST'
}
}
Run Code Online (Sandbox Code Playgroud)
用PHP可以吗?
Jan*_*čič 60
您可以使用反射API获取它们
我假设您希望根据变量的值(变量值==常量值)得到常量的名称.获取类中定义的所有常量,循环它们并将这些常量的值与变量的值进行比较.请注意,使用此方法,如果有两个具有相同值的常量,则可能会获得所需的常量.
例:
class Foo {
const ERR_SOME_CONST = 6001;
const ERR_SOME_OTHER_CONST = 5001;
function bar() {
$x = 6001;
$fooClass = new ReflectionClass ( 'Foo' );
$constants = $fooClass->getConstants();
$constName = null;
foreach ( $constants as $name => $value )
{
if ( $value == $x )
{
$constName = $name;
break;
}
}
echo $constName;
}
}
Run Code Online (Sandbox Code Playgroud)
ps:你介意说你为什么需要这个,因为这似乎很不寻常......
dea*_*ror 28
这就是我为实现它所做的.受Jan Hancic的启发.
class ErrorCode
{
const COMMENT_NEWCOMMENT_DISABLED = -4;
const COMMENT_TIMEBETWEENPOST_ERROR = -3;
/**
* Get error message of a value. It's actually the constant's name
* @param integer $value
*
* @return string
*/
public static function getErrorMessage($value)
{
$class = new ReflectionClass(__CLASS__);
$constants = array_flip($class->getConstants());
return $constants[$value];
}
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*ano 13
有了反思:
$class = new ReflectionClass("Foo");
$constants = $class->getConstants();
Run Code Online (Sandbox Code Playgroud)
$constants
是一个数组,它包含类Foo中定义的常量的所有名称和值.
rae*_*kid 10
我知道这是一个老问题,但我仍然觉得我有一些有用的输入.我使用我的所有枚举扩展的抽象类来实现它.抽象类包含一个通用的toString()方法;
abstract class BaseEnum{
private final function __construct(){ }
public static function toString($val){
$tmp = new ReflectionClass(get_called_class());
$a = $tmp->getConstants();
$b = array_flip($a);
return ucfirst(strtolower($b[$val]));
}
}
//actual enum
final class UserType extends BaseEnum {
const ADMIN = 10;
const USER = 5;
const VIEWER = 0;
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以在扩展基本枚举的每个枚举上获得用于输出的人类可读字符串.此外,你的枚举的实施,正在final
,不能延长,因为在构造函数BaseEnum
是private
它不能被实例化.
例如,如果您显示所有用户名及其类型的列表,您可以执行类似的操作
foreach($users as $user){
echo "<li>{$user->name}, ".UserType::toString($user->usertype)."</li>";
}
Run Code Online (Sandbox Code Playgroud)
所有其他答案都涵盖了基本要点.但是,如果疯狂的一个衬里是你的事,那么:
function getConstantName($class, $value)
{
return array_flip((new \ReflectionClass($class))->getConstants())[$value];
}
Run Code Online (Sandbox Code Playgroud)
如果你需要处理值可能实际上不是常量之一的情况,那么你可以放弃一个额外的行:
function getConstantName($class, $value)
{
$map = array_flip((new \ReflectionClass($class))->getConstants());
return (array_key_exists($value, $map) ? $map[$value] : null);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
可以使用此函数将所有常量分配给数组。
$const = get_defined_constants();
Run Code Online (Sandbox Code Playgroud)
然后使用以下函数可以打印数组结构
echo "<pre>";
print_r($const);
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到更多的解释www.sugunan.com