如何检查名称空间中是否存在类? [英] How to check if class exists within a namespace?

查看:53
本文介绍了如何检查名称空间中是否存在类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

    use XXX\Driver\Driver;

...

var_dump(class_exists('Driver')); // false
        $driver = new Driver(); // prints 123123123 since I put an echo in the constructor of this class
        exit;

好吧……这种行为是很不合理的(根据PHP创建不存在的类的对象).有什么方法可以检查给定名称空间下是否存在类?

Well... this behaviour is quite irrational (creating objects of classes that according to PHP do not exist). Is there any way to check if a class exist under given namespace?

推荐答案

要检查类,您必须使用名称空间(完整路径)指定它:

In order to check class you must specify it with namespace, full path:

namespace Foo;
class Bar
{
}

var_dump(class_exists('Bar'), class_exists('\Foo\Bar')); //false, true

-即您必须指定上课的完整路径.您在名称空间而不是全局上下文中定义它.

-i.e. you must specify full path to class. You defined it in your namespace and not in global context.

但是,如果您确实像在示例中一样在名称空间中导入了该类,则可以通过导入的名称而不使用名称空间来引用它,但这不允许您在动态构造中尤其是在内部进行操作.组成类名的行字符串.例如,以下所有操作都会失败:

However, if you do import the class within the namespace like you do in your sample, you can reference it via imported name and without namespace, but that does not allow you to do that within dynamic constructions and in particular, in-line strings that forms class name. For example, all following will fail:

namespace Foo;
class Bar {
    public static function baz() {} 
}

use Foo\Bar;

var_dump(class_exists('Bar')); //false
var_dump(method_exists('Bar', 'baz')); //false

$ref = "Bar";
$obj = new $ref(); //fatal

,依此类推.问题在于处理导入别名的机制.因此,在使用此类构造时,您必须指定完整路径:

and so on. The issue lies within the mechanics of working for imported aliases. So when working with such constructions, you have to specify full path:

var_dump(class_exists('\Foo\Bar')); //true
var_dump(method_exists('\Foo\Bar', 'baz')); //true

$ref = 'Foo\Bar';
$obj = new $ref(); //ok

这篇关于如何检查名称空间中是否存在类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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