Is it possible to get list of defined namespaces in PHP


Given file 1 has namespace ns_1 and file 2 has namespace ns_2, if file 1 and file 2 are included in file 3, there is no way to know that namespaces ns_1 and ns_2 have been loaded.

The only way is to use the ‘class_exists’ function and the list of classes with the specific namespace can be obtained using ‘get_declared_classes’. Simply put, this data obtained can be used to find a matching namespace given all the declared class names −

function namespaceExists($namespace) {
   $namespace .= "\";
   foreach(get_declared_classes() as $name)
   if(strpos($name, $namespace) === 0) return true;
   return false;
}

----Or---

Example

 Live Demo

<?php
namespace FirstNamespace;
class new_class {}
namespace SecondNamespace;
class new_class {}
namespace ThirdNamespace\FirstSubNamespace;
class new_class {}
namespace ThirdNamespace\SecondSubNamespace;
class new_class {}
namespace SecondNamespace\FirstSubNamespace;
class new_class {}
$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);

Output

This will produce the following output −

Array ( [FirstNamespace] => [SecondNamespace] => Array ( [FirstSubNamespace] => ) [ThirdNamespace] => Array ( [FirstSubNamespace] => [SecondSubNamespace] => ) )

Different namespaces are created (FirstNamespace, SecondNamespace..) and empty class is declared (new_class). An array of namespaces is created and a foreach loop runs through the classes that are declared. A regular expression match is done and the namespaces that are defined in that specific environment will be displayed.

Updated on: 09-Apr-2020

417 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements