jeudi 4 janvier 2018

Why can't I instantiate a new object from a string without a full namespace

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).





Aucun commentaire:

Enregistrer un commentaire