Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to get list of defined namespaces

Tags:

namespaces

php

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

like image 699
DonSeba Avatar asked Mar 07 '11 22:03

DonSeba


People also ask

How many namespaces are allowed in the model definition file?

Defining multiple namespaces in the same file ¶ Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.


1 Answers

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 ThirdNamespace\FirstSubNamespace; class Bar {}  namespace ThirdNamespace\SecondSubNamespace; class Bar {}  namespace SecondNamespace\FirstSubNamespace; 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] =>           ) ) 
like image 89
Hamish Avatar answered Sep 29 '22 17:09

Hamish