我正在尝试访问我的一个类中的类常量:
const MY_CONST = "value";
如果我有一个变量保存这个常量的名称,如下所示:
$myVar = "MY_CONST";
我可以以某种方式访问 MY_CONST 的值吗?
self::$myVar
这显然不起作用,因为它是针对静态属性的。 另外,变量变量也不起作用。
有两种方法可以做到这一点:使用 constant 函数或使用 reflection。
常量函数适用于通过
define
声明的常量以及类常量:
class A
{
const MY_CONST = 'myval';
static function test()
{
$c = 'MY_CONST';
return constant('self::'. $c);
}
}
echo A::test(); // output: myval
第二种更费力的方法是通过反思:
$ref = new ReflectionClass('A');
$constName = 'MY_CONST';
echo $ref->getConstant($constName); // output: myval
没有相应的语法,但您可以使用显式查找:
print constant("classname::$myConst");
我相信它也适用于
self::
。
我可以以某种方式访问 MY_CONST 的值吗?
self::MY_CONST
如果要动态访问,可以使用 reflection API Docs:
$myvar = 'MY_CONST';
$class = new ReflectionClass(self);
$const = $class->getConstant($myVar);
反射 API 的好处是您可以一次获取所有常量 (
getConstants
)。
如果您不喜欢反射 API,因为您不想使用它,替代方案是
constant
函数(Demo):
$myvar = 'MY_CONST';
class foo {const MY_CONST = 'bar';}
define('self', 'foo');
echo constant(self.'::'.$myvar);
Reflection 请注意:ReflectionClass 的构造函数必须接收该类的“完整路径”作为其参数。 这意味着仅将字符串“A”设置为构造函数参数在某些情况下可能不起作用。 为了避免这个问题,在使用ReflectionClass时,这样做会更好:
$classA = new A();
$name_classA = get_class($classA);
$ref = new ReflectionClass(get_class($name_classA));
$constName = 'MY_CONST';
echo $ref->getConstant($constName);
每当您在代码中时,函数 get_class 都会为您提供类的完整路径。缺少完整路径可能会导致“找不到类”PHP 错误。
$myVar = MY_CONST or $myVar = $MY_CONST