Ben*_*Ben 108 php class-constants
我希望能够做到这样的事情:
class ThingIDs
{
const Something = 1;
const AnotherThing = 2;
}
$thing = 'Something';
$id = ThingIDs::$thing;
Run Code Online (Sandbox Code Playgroud)
这不起作用.做一些等效的直接方式吗?请注意,我坚持上课; 它在图书馆我无法重写.我正在编写在命令行上接受参数的代码,我真的希望它采用符号名而不是id号.
Dan*_*mon 174
$id = constant("ThingIDs::$thing");
http://php.net/manual/en/function.constant.php
Phi*_*hil 25
使用反射
$r = new ReflectionClass('ThingIDs');
$id = $r->getConstant($thing);
Run Code Online (Sandbox Code Playgroud)
Jor*_*oon 12
如果使用名称空间,则应该在类中包含名称空间.
echo constant('My\Application\ThingClass::ThingConstant');
Run Code Online (Sandbox Code Playgroud)
您可以使用这样的函数:
\n\nfunction class_constant($class, $constant)\n{\n if ( ! is_string($class)) {\n $class = get_class($class);\n }\n\n return constant($class . '::' . $constant);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n它需要两个参数:
\n\n如果传递一个对象实例,则会推断其类名。如果您使用 PHP\xc2\xa07,则可以使用::class传递适当的类名而无需考虑命名空间。
class MyClass\n{\n const MY_CONSTANT = 'value';\n}\n\nclass_constant('MyClass', 'MY_CONSTANT'); # 'value'\nclass_constant(MyClass::class, 'MY_CONSTANT'); # 'value' (PHP\xc2\xa07 only)\n\n$myInstance = new MyClass;\nclass_constant($myInstance, 'MY_CONSTANT'); # 'value'\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
26723 次 |
| 最近记录: |