Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Is it possible to get list of defined namespaces in PHP
PHP doesn't provide a direct built−in function to list all defined namespaces. However, you can determine if a namespace exists by examining the classes within it using get_declared_classes() and class_exists().
Method 1: Check if Namespace Exists
This approach checks whether a specific namespace has been loaded by looking for classes within it ?
<?php
function namespaceExists($namespace) {
$namespace .= "";
foreach(get_declared_classes() as $name) {
if(strpos($name, $namespace) === 0) {
return true;
}
}
return false;
}
// Test the function
namespace TestNamespace;
class TestClass {}
// Check if namespace exists
if (namespaceExists('TestNamespace')) {
echo "TestNamespace exists<br>";
} else {
echo "TestNamespace does not exist<br>";
}
?>
TestNamespace exists
Method 2: Extract All Namespaces
This method builds a hierarchical array of all namespaces by parsing declared class names ?
<?php
namespace FirstNamespace;
class NewClass {}
namespace SecondNamespace;
class NewClass {}
namespace ThirdNamespace\FirstSubNamespace;
class NewClass {}
namespace ThirdNamespace\SecondSubNamespace;
class NewClass {}
namespace SecondNamespace\FirstSubNamespace;
class NewClass {}
$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] =>
)
)
How It Works
The extraction method uses a regular expression @[^\\]+(?=\\)@iU to find namespace parts in class names. It builds a nested array structure representing the namespace hierarchy by iterating through each class name and parsing its namespace components.
Key Points
- Limitation: Only namespaces containing classes can be detected
- Performance: Method 1 is faster for checking specific namespaces
- Scope: Both methods only work with already loaded/included files
Conclusion
While PHP lacks native namespace introspection, you can detect loaded namespaces by examining declared classes. Use Method 1 for simple existence checks and Method 2 for comprehensive namespace discovery.
