使用包含常量名称的简单变量访问类常量 [英] Accessing a class constant using a simple variable which contains the name of the constant
本文介绍了使用包含常量名称的简单变量访问类常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试访问我的类中的类常量:
I'm trying to access a class constant in one of my classes:
const MY_CONST = "value";
如果我有一个变量保存这个常量的名字,如下:
If I have a variable which holds the name of this constant like this:
$myVar = "MY_CONST";
我可以访问MY_CONST的值吗?
Can I access the value of MY_CONST somehow?
self::$myVar
因为它是静态属性。
变量变量也不起作用。
does not work obviously because it is for static properties. Variable variables does not work either.
推荐答案
There are two ways to do this: using the constant function or using reflection.
define
以及类常量:
class A
{
const MY_CONST = 'myval';
static function test()
{
$c = 'MY_CONST';
return constant('self::'. $c);
}
}
echo A::test(); // output: myval
反射类
第二个更麻烦的方式是通过反射:
Reflection Class
A second, more laborious way, would be through reflection:
$ref = new ReflectionClass('A');
$constName = 'MY_CONST';
echo $ref->getConstant($constName); // output: myval
这篇关于使用包含常量名称的简单变量访问类常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文