Can anyone explain why the below code causes a "Cannot find class" error? Instantiating the class with the fully qualified name works, but eliminates the advantage of the "use" statement.
<?php
namespace
{
use Foo\Bar;
new Bar; // Works
$class = 'Foo\Bar';
new $class; // Works
$class = 'Bar';
new $class; // "Cannot find class" error
}
namespace Foo
{
class Bar {}
}
Thanks
Well, I suppose it's actually a feature. And aliases won't help here, for the same reasons:
Importing is performed at compile-time, and so does not affect dynamic class, function or constant names. [...]
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$a = 'Another';
$obj = new $a; // instantiates object of class Another
?>
And yes, it sorts of defeats the purpose of use
with dynamic classes.