Reputation: 36544
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!
Upvotes: 12
Views: 2699
Reputation: 6859
Check this class and 'getUseStatements' method.
Or this class and 'getNamespaceAliases' method.
Or perhaps simplified
https://github.com/vaniocz/type-parser/blob/master/src/UseStatementsParser.php
Upvotes: 6
Reputation: 534
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);
Upvotes: 0
Reputation: 2493
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).
Upvotes: 0
Reputation: 856
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
Upvotes: 3