Is there a namespace aware alternative to PHP'

2020-08-11 10:34发布

问题:

If you try using class_exists() inside a method of a class in PHP you have to specify the full name of the class--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 properly autoloads) and looks like this

   namespace Foo;

    class Boo{
       // stuff in here
    }

if I try:

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

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

回答1:

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

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

It's not difficult, and it makes it absolutely clear what you're referring to. Remember, you should be going for readability. Namespace imports are handy for writing, but make reading confusing (because you need to keep in mind the current namespace and any imports when reading code).

However, in 5.5, there's a new construct coming:

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

The class pseudo magic constant can be put onto any identifier and it will return the fully qualified class name that it will resolve to.......