Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP5: get imported namespaces list

Is it possible to get a list of all imported classes/namespaces in a PHP file, in the current context?

For example:

namespace A;
use B, C\D;

I'd like to get this array:

array('B', 'C\D');

The reason is that I'm building a Mapper Registry, and I'd like to be able to query this mapper using the aliased class name in the current context, and no the full name.

For example:

$registry->getMapper('D');

Instead of:

$registry->getMapper('C\D');

And if possible, I'd like not to hardcode these aliases, if there is a way to get them automatically from PHP!

like image 662
BenMorel Avatar asked Aug 11 '11 12:08

BenMorel


2 Answers

Check this class and 'getUseStatements' method.

https://github.com/doctrine/common/blob/2.8/lib/Doctrine/Common/Reflection/StaticReflectionParser.php

Or this class and 'getNamespaceAliases' method.

https://github.com/Andrewsville/PHP-Token-Reflection/blob/master/TokenReflection/ReflectionFileNamespace.php

Or perhaps simplified

https://github.com/vaniocz/type-parser/blob/master/src/UseStatementsParser.php

like image 164
maryo Avatar answered Oct 06 '22 17:10

maryo


This was discussed recently on the PHP Internals mailing list. The short answer (as I understand it) is no. http://marc.info/?l=php-internals&m=130815747804590&w=2

like image 31
H Hatfield Avatar answered Oct 06 '22 19:10

H Hatfield