BenMorel
BenMorel

Reputation: 36544

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!

Upvotes: 12

Views: 2699

Answers (4)

Rex Schrader
Rex Schrader

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

Ernestas Stankevičius
Ernestas Stankevičius

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

H Hatfield
H Hatfield

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

Related Questions