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
如果文件 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.
其次,您可以使用 with namespace" rel="noreferrer">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] =>
)
)
这篇关于是否可以获得已定义名称空间的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以获得已定义名称空间的列表
基础教程推荐
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
