HI there,
I was wondering if there is a way in php 5.3+ to get a list of defined namespaces within an application.
so
if
file 1 has namespace FOO
and
file 2 has namespace 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.
I want to achieve this to be sure an module in my application is loaded before checking if the class exists ( with is_callable ).
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
My Answer:
In PHP, there is no built-in function to get a list of defined namespaces within an application. However, you can achieve this by using reflection.
You can use the `get_declared_classes()` function to get a list of all defined classes in the application. Then, you can use reflection to check the namespace of each class and build a list of unique namespaces.
Here is an example code snippet to achieve this:
php
$namespaces = array();
$classes = get_declared_classes();
foreach ($classes as $class) {
$reflection = new ReflectionClass($class);
$namespace = $reflection->getNamespaceName();
if (!in_array($namespace, $namespaces)) {
$namespaces[] = $namespace;
}
}
print_r($namespaces);
This code will give you a list of unique namespaces that are defined in your application. You can then check if a specific namespace is defined by using the `in_array()` function.
php
if (in_array('FOO', $namespaces)) {
echo 'Namespace FOO is defined';
} else {
echo 'Namespace FOO is not defined';
}
I hope this helps! Let me know if you have any further questions.
Rate this post
5 of 5 based on 6819 votesComments