Is there an alternative to PHP with a namespace known as namespace ()?

If you try to use class_exists () inside a class method in PHP, you need to specify the fully qualified class name - the current namespace is not respected. For example, if my class is:

<? namespace Foo; class Bar{ public function doesBooClassExist(){ return class_exists('Boo'); } } 

And Boo is a class (which loads automatically) and looks like this:

  namespace Foo; class Boo{ // stuff in here } 

if i try:

 $bar = new Bar(); $success = $bar->doesBooClassExist(); var_dump($success); 

you get false ... is there an alternative way to do this without explicitly specifying the full class name (i.e. class_exits('Foo\Boo') )?

+11
php namespaces
Apr 05 '13 at 16:49 on
source share
1 answer

Prior to version 5.5, the best way is to always use the fully qualified class name:

 public function doesBooClassExist() { return class_exists('Foo\Boo'); } 

It is not difficult, and it is absolutely clear what you are talking about. Remember, you must go for readability. Importing a namespace is convenient for writing, but makes reading confusing (because you need to keep in mind the current namespace and any imports when reading the code).

However, a new design appeared in 5.5:

 public function doesBooClassExist() { return class_exists(Boo::class); } 

The pseudo-magic class constant can be placed in any identifier, and it will return the full name of the class, which will be resolved ........

+23
Apr 05 '13 at
source share



All Articles