是否可以获得已定义名称空间的列表 [英] is it possible to get list of defined namespaces

查看:105
本文介绍了是否可以获得已定义名称空间的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我想知道 php 5.3+ 中是否有一种方法可以在应用程序中获取已定义名称空间的列表.所以

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

如果文件 1 有命名空间 FOO文件 2 有命名空间 BAR

现在,如果我在文件 3 中包含文件 1 和文件 2,我想通过某种函数调用来知道命名空间 FOO 和 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.

我想实现这一点,以确保在检查类是否存在之前加载我的应用程序中的模块(使用 is_callable ).

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

如果这不可能,我想知道是否有一个函数来检查是否定义了特定的命名空间,比如 is_namespace().

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

推荐答案

首先,查看一个类是否存在,使用class_exists.

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

其次,您可以使用 get_declared_classes.

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

给予:

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

        )
)

这篇关于是否可以获得已定义名称空间的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆