获取 PHP 中动态选择的类常量的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6147102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get value of dynamically chosen class constant in PHP
提问by Ben
I would like to be able to do something like this:
我希望能够做这样的事情:
class ThingIDs
{
const Something = 1;
const AnotherThing = 2;
}
$thing = 'Something';
$id = ThingIDs::$thing;
This doesn't work. Is there a straightforward way of doing something equivalent? Note that I'm stuck with the class; it's in a library I can't rewrite. I'm writing code that takes arguments on the command line, and I would reallylike it to take symbolic names instead of id numbers.
这不起作用。有没有一种简单的方法可以做等效的事情?请注意,我被困在课堂上;它在我无法重写的库中。我正在编写在命令行上接受参数的代码,我真的希望它采用符号名称而不是 ID 编号。
回答by Dan Simon
$id = constant("ThingIDs::$thing");
$id = constant("ThingIDs::$thing");
回答by Phil
Use Reflection
使用反射
$r = new ReflectionClass('ThingIDs');
$id = $r->getConstant($thing);
回答by Jordi Kroon
If you are using namespaces, you should include the namespace with the class.
如果使用命名空间,则应在类中包含命名空间。
echo constant('My\Application\ThingClass::ThingConstant');
回答by Josh
<?php
class Dude {
const TEST = 'howdy';
}
function symbol_to_value($symbol, $class){
$refl = new ReflectionClass($class);
$enum = $refl->getConstants();
return isset($enum[$symbol])?$enum[$symbol]:false;
}
// print 'howdy'
echo symbol_to_value('TEST', 'Dude');
回答by Glutexo
Helper function
辅助功能
You can use a function like this:
您可以使用这样的函数:
function class_constant($class, $constant)
{
if ( ! is_string($class)) {
$class = get_class($class);
}
return constant($class . '::' . $constant);
}
It takes two arguments:
它需要两个参数:
- Class name or object instance
- Class constant name
- 类名或对象实例
- 类常量名
If an object instance is passed, its class name is inferred. If you use PHP?7, you can use ::class
to pass appropriate class name without having to think about namespaces.
如果传递了一个对象实例,则推断其类名。如果您使用 PHP?7,您可以使用::class
传递适当的类名而不必考虑名称空间。
Examples
例子
class MyClass
{
const MY_CONSTANT = 'value';
}
class_constant('MyClass', 'MY_CONSTANT'); # 'value'
class_constant(MyClass::class, 'MY_CONSTANT'); # 'value' (PHP?7 only)
$myInstance = new MyClass;
class_constant($myInstance, 'MY_CONSTANT'); # 'value'
回答by Andrei
My problem was similiar to this subject. When you have the object, but not the class name, you could use:
我的问题类似于这个主题。当您拥有对象但没有类名时,您可以使用:
$class_name = get_class($class_object);
$class_const = 'My_Constant';
$constant_value = constant($class_name.'::'.$class_const);
回答by crmpicco
If you have a reference to the class itself then you can do the following:
如果您有对类本身的引用,则可以执行以下操作:
if (defined(get_class($course). '::COURSES_PER_INSTANCE')) {
// class constant is defined
}