Jinsong Li
Jinsong Li

Reputation: 7378

PHP: how to dynamically create class from imported namespace?

I searched around and can not get an answer, so I am here.

In my PHP file, I import some namespaces, and later, I want to dynamically create one of the imported classes, but it is not working, it seems PHP must need the complete class path to dynamically create class, only the alias of imported namespace will not do it. code sample:
use some\foo; //import foo class
$b = 'foo'; $fullpath_b = 'some\foo';
$fullpath_b::static_function(); //this will work $b::static_function(); //this will not work

my question is, I have only the alias of the imported class 'foo', not the full path class 'some\foo', how can I possibly get the full path name of 'foo', so that I can create the class out of it? If I use new ReflectionClass() to create class, it also need a full path.
note: I do not need to create a object of the class, only need the class.

Thanks for your opinion.

Upvotes: 0

Views: 1198

Answers (1)

Philipp
Philipp

Reputation: 15629

Importing is performed at compile-time and there is currently no way to determine the imported aliases. There's a rfc to add such functionallity to reflection, but it seems this will be rejected.

So you have to use the FQN for the class if you want to use them in Reflection or to create them dynamically (http://php.net/manual/en/language.namespaces.importing.php)

Upvotes: 1

Related Questions