使用包含常量名称的简单变量访问类常量
我正在尝试访问我的一个类中的类常量:
const MY_CONST = "value";
如果我有一个变量保存该常量的名称,如下所示:
$myVar = "MY_CONST";
我可以以某种方式访问 MY_CONST 的值吗?
self::$myVar
这显然不起作用,因为它适用于静态属性。 此外,变量变量也不起作用。
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";
Can I access the value of MY_CONST somehow?
self::$myVar
This is not working obviously because it is for static properties.
Also, Variable variables does not work either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有两种方法可以做到这一点:使用 constant 函数或使用 反射。
常量函数
常量函数与通过
define
声明的常量以及类常量一起使用:反射类
第二种更费力的方法是通过反射:
There are two ways to do this: using the constant function or using reflection.
Constant Function
The constant function works with constants declared through
define
as well as class constants:Reflection Class
A second, more laborious way, would be through reflection:
没有相应的语法,但您可以使用显式查找:
我相信它也适用于
self::
。There is no syntax for that, but you can use an explicit lookup:
I believe it also works with
self::
.如果要动态访问,可以使用 reflection API Docs :
反射 API 的好处是您可以一次获取所有常量 (
getConstants
)。如果您因为不想使用反射 API 而不喜欢它,则另一种选择是
constant
函数 (演示):If you want to access is dynamically, you can use the reflection API Docs:
The benefit with the reflection API can be that you can get all constants at once (
getConstants
).If you dislike the reflection API because you don't wanna use it, an alternative is the
constant
function (Demo):Reflection 需要注意的是:ReflectionClass 的构造函数必须接收类的完整路径作为其参数。
这意味着在某些情况下,仅将字符串“A”设置为构造函数参数可能不起作用。
为了避免这个问题,当使用 ReflectionClass 时,如果这样做会更好:
每当您在代码中时,函数 get_class 都会为您提供类的完整路径。缺少完整路径可能会导致“找不到类”PHP 错误。
Just a note for Reflection: the constructor for ReflectionClass must receive the full path of the class for its parameter.
This means that just setting the string 'A' as a constructor parameter may not work in some cases.
To avoid this problem, when using ReflectionClass you will be better if you do this:
Function get_class will give you the full path of a class whenever you are in the code. Missing the full path may result in a "Class not found" PHP error.
你试过吗
have you tried
IMO 这个解决方案比现有的解决方案稍好:
self
使用constant(self::class . “::$v”);
IMO this solution is slightly better than the existing ones:
self
useconstant(self::class . "::$v");