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?
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:As you have already written in your question, you have found a "solution" by providing that fully qualified classname:
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: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 useclass_alias
to get it to work. Use it in replace of theuse \Some\Foo\Bar
to get your desired behaviour: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.