例
<?php
function get_namespace_items($namespace, $include_sub_namespaces = false) {
$namespace = trim($namespace, '\\') . '\\';
$classes = get_declared_classes();
$interfaces = get_declared_interfaces();
$traits = get_declared_traits();
$functions = get_defined_functions();
$constants = get_defined_constants();
$filter = function ($items) use ($namespace, $include_sub_namespaces) {
$matched = [];
foreach ($items as $item) {
if (strpos($item, $namespace) === 0) {
if (
$include_sub_namespaces ||
strpos(substr($item, strlen($namespace)), '\\') === false
) {
$matched[] = $item;
}
}
}
return $matched;
};
return [
'class' => $filter($classes),
'interface' => $filter($interfaces),
'trait' => $filter($traits),
'function' => $filter($functions['user']),
'constant' => $filter(array_keys($constants)),
];
}
require_once("./def.php");
var_dump(get_namespace_items('\\foo\\bar', false));
var_dump(get_namespace_items('\\foo\\bar', true));
def.php
<?php
namespace foo\bar;
function f() {}
class C {}
abstract class A {}
trait T {}
interface I {}
const c = 1;
define('d', 2);
namespace foo\bar\baz;
function ff() {}
結果
array(5) {
["class"]=>
array(2) {
[0]=>
string(9) "foo\bar\C"
[1]=>
string(9) "foo\bar\A"
}
["interface"]=>
array(1) {
[0]=>
string(9) "foo\bar\I"
}
["trait"]=>
array(1) {
[0]=>
string(9) "foo\bar\T"
}
["function"]=>
array(1) {
[0]=>
string(9) "foo\bar\f"
}
["constant"]=>
array(1) {
[0]=>
string(9) "foo\bar\c"
}
}
array(5) {
["class"]=>
array(2) {
[0]=>
string(9) "foo\bar\C"
[1]=>
string(9) "foo\bar\A"
}
["interface"]=>
array(1) {
[0]=>
string(9) "foo\bar\I"
}
["trait"]=>
array(1) {
[0]=>
string(9) "foo\bar\T"
}
["function"]=>
array(2) {
[0]=>
string(9) "foo\bar\f"
[1]=>
string(14) "foo\bar\baz\ff"
}
["constant"]=>
array(1) {
[0]=>
string(9) "foo\bar\c"
}
}