Get value of dynamically chosen class constant in PHP

陌路散爱 提交于 2019-11-28 18:30:20
Dan Simon

$id = constant("ThingIDs::$thing");

http://php.net/manual/en/function.constant.php

Use Reflection

$r = new ReflectionClass('ThingIDs');
$id = $r->getConstant($thing);

If you are using namespaces, you should include the namespace with the class.

echo constant('My\Application\ThingClass::ThingConstant'); 
<?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');

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.

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'

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!