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] =>
)
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…