Can't get constant from dynamic class using namespaces

前端 未结 1 1179
一向
一向 2021-01-03 08:37

I\'m not able to get a constant from a class which is defined by using a string variable and PHP 5.3. namespaces. Example:

use \\Some\\Foo\\Bar;

$class = \'         


        
相关标签:
1条回答
  • 2021-01-03 09:07

    Using $class::CONST to get a class constant, it is required that $class contains a fully qualified classname independent to the current namespace.

    The use statement does not help here, even if you were in the namespace \Some\Foo, the following would not work:

    namespace \Some\Foo;
    
    $class = 'Bar';
    echo $class::LOCATION;
    

    As you have already written in your question, you have found a "solution" by providing that fully qualified classname:

    use \Some\Foo\Bar;
    
    $class = "\Some\Foo\Bar";
    echo $class::LOCATION;
    

    However, you dislike this. I don't know your specific problem with it, but generally it looks fine. If you want to resolve the full qualified classname of Bar within your current namespace, you can just instantiate an object of it and access the constant:

    use \Some\Foo\Bar;
    
    $class = new Bar;
    echo $class::LOCATION;
    

    At this stage you do not even need to care in which namespace you are.

    If you however for some reason need to have a class named Bar in the global namespace, you can use class_alias to get it to work. Use it in replace of the use \Some\Foo\Bar to get your desired behaviour:

    class_alias('\Some\Foo\Bar', 'Bar');
    
    $class = 'Bar';
    echo $class::LOCATION;
    

    But anyway, I might not get your question, because the solution you already have looks fine to me. Maybe you can write what your specific problem is.

    0 讨论(0)
提交回复
热议问题