Get value of dynamically chosen class constant in PHP

前端 未结 8 1194
无人共我
无人共我 2020-11-29 03:38

I would like to be able to do something like this:

class ThingIDs
{
    const Something = 1;
    const AnotherThing = 2;
}

$thing = \'Something\';
$id = Thi         


        
8条回答
  •  被撕碎了的回忆
    2020-11-29 04:09

    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'
    

提交回复
热议问题