Reputation: 13313
Why is it that when I want to instantiate a new object from a string like so
use Foo\Bar\Test
$name = "Test";
$test = new $name();
I get an exception since Test
is not found in the global namespace.
I know I could simply use the full namespace when instantiating :
$name = "Foo\\Bar\\Test";
$test = new $name();
But it kind of doesn't fit the use I planned to make out of it. I know it's probably a design flaw on my part for the "doesn't fit" but it still raised the question as to why this cannot be done. Also, if it exists, are there alternatives to this approach? (beside __NAMESPACE__
as in this example I am not currently in Foo\Bar
).
Upvotes: 3
Views: 123
Reputation: 15629
You have to differentiate between the information, the compiler resolves at compile and at runtime. At compiletime he resolves alias resolution.
use Foo\Bar\Test
So every occurance of Test
would be resolved to \Foo\Bar\Test
.
Creating new objects instead is an runtime operation. At this point, there isn't any alias or namespace resolution. The only thing the runtime (new
operator) knows at this time, is the given name. If you pass a class, it must always be the full qualified name.
Upvotes: 3