是否有名称空间替代PHP的class_exists()? [英] Is there a namespace aware alternative to PHP's class_exists()?

查看:138
本文介绍了是否有名称空间替代PHP的class_exists()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果尝试在PHP的类的方法内使用class_exists(),则必须指定类的全名-不尊重当前的名称空间.例如,如果我的班级是:

 <?
    namespace Foo;

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

Boo是一个类(可以自动加载),看起来像这样

   namespace Foo;

    class Boo{
       // stuff in here
    }

如果我尝试:

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

您会得到一个错误...是否有另一种方法可以执行此操作而不必显式指定完整的类名(即class_exits('Foo\Boo'))?

解决方案

在5.5之前,最好的方法是始终使用完全限定的类名:

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

这并不困难,而且它绝对清楚您要指的是什么.记住,您应该为了可读性而去.命名空间导入很容易编写,但是会使阅读变得混乱(因为在读取代码时,您需要牢记当前的命名空间和任何导入).

但是,在5.5中,有一个新的构造:

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

class伪魔术常数可以放在任何标识符上,并将返回解析为的完全合格的类名称.

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') )?

解决方案

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.......

这篇关于是否有名称空间替代PHP的class_exists()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆