Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

php - is it possible to get list of defined namespaces

HI there,

I was wondering if there is a way in php 5.3+ to get a list of defined namespaces within an application. so

if file 1 has namespace FOO and file 2 has namespace BAR

Now if i include file 1 and file 2 in file 3 id like to know with some sort of function call that namespace FOO and BAR are loaded.

I want to achieve this to be sure an module in my application is loaded before checking if the class exists ( with is_callable ).

If this is not possible i'd like to know if there is a function to check if a specific namespace is defined, something like is_namespace().

Hope you get the idea. and what i'm trying to achieve

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Firstly, to see if a class exists, used class_exists.

Secondly, you can get a list of classes with namespace using get_declared_classes.

In the simplest case, you can use this to find a matching namespace from all declared class names:

function namespaceExists($namespace) {
    $namespace .= "";
    foreach(get_declared_classes() as $name)
        if(strpos($name, $namespace) === 0) return true;
    return false;
}

Another example, the following script produces a hierarchical array structure of declared namespaces:

<?php
namespace FirstNamespace;
class Bar {}

namespace SecondNamespace;
class Bar {}

namespace ThirdNamespaceFirstSubNamespace;
class Bar {}

namespace ThirdNamespaceSecondSubNamespace;
class Bar {}

namespace SecondNamespaceFirstSubNamespace;
class Bar {}

$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);

Gives:

Array
(
    [FirstNamespace] => 
    [SecondNamespace] => Array
        (
            [FirstSubNamespace] => 
        )
    [ThirdNamespace] => Array
        (
            [FirstSubNamespace] => 
            [SecondSubNamespace] => 

        )
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...