是否有可能获得已定义名称空间的列表 [英] is it possible to get list of defined namespaces
问题描述
我想知道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
如果
file 1 has namespace FOO
和
file 2 has namespace BAR
if
file 1 has namespace FOO
and
file 2 has namespace BAR
现在,如果我在文件3 id中包含文件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
推荐答案
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 ThirdNamespace\FirstSubNamespace;
class Bar {}
namespace ThirdNamespace\SecondSubNamespace;
class Bar {}
namespace SecondNamespace\FirstSubNamespace;
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屋!