Can't get constant from dynamic class using na

2019-02-11 02:47发布

问题:

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 = 'Bar';
echo $class::LOCATION;

where LOCATION is a properly defined constant. The error I get says class Bar is undefined.

If I instead do

$class = "\Some\Foo\Bar";

everything works fine.

Is there anyway to make the first example work?

回答1:

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.