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 possibl开发者_C百科e, I'd like not to hardcode these aliases, if there is a way to get them automatically from PHP!
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
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
The only way to do so, on your main __construct(), read classes dir, for all available php files for namespaces. (PHP Manual: glob() - Answer 101017).
The top answer for this question: is it possible to get list of defined namespaces
Has some very handy code which can enumerate all namespaces:
$namespaces=array();
foreach(get_declared_classes() as $name) {
if(preg_match_all("@[^\\\]+(?=\\\)@iU", $name, $matches)) {
$matches = $matches[0];
$parent =&$namespaces;
while(count($matches)) {
$match = array_shift($matches);
if(!isset($parent[$match]) && count($matches))
$parent[$match] = array();
$parent =&$parent[$match];
}
}
}
print_r($namespaces);
精彩评论