php 如何检查名称空间中是否存在类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22407370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:54:51  来源:igfitidea点击:

How to check if class exists within a namespace?

phpoopnamespaces

提问by Taruo Gene

I've got this:

我有这个:

    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;

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?

嗯...这种行为是非常不合理的(创建根据 PHP 不存在的类的对象)。有没有办法检查给定命名空间下是否存在类?

回答by Alma Do

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

为了检查类,您必须使用命名空间、完整路径指定它:

namespace Foo;
class Bar
{
}

and

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

-i.e. you mustspecify 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

回答by outis

The issue (as mentioned in the class_exists()manual page user notes) is that aliases aren't taken into account whenever a class name is given as a string. This also affects other functions that take a class name, such as is_a(). Consequently, if you give the class name in a string, you must include the full namespace (e.g. '\XXX\Driver\Driver', 'XXX\\Driver\\Driver').

问题(如class_exists()手册页用户注释中所述)是,每当将类名作为字符串给出时,都不会考虑别名。这也会影响采用类名的其他函数,例如is_a(). 因此,如果在字符串中给出类名,则必须包含完整的命名空间(例如'\XXX\Driver\Driver', 'XXX\\Driver\\Driver')。

PHP 5.5 introduced the classconstant for just this purpose:

PHP 5.5class为此目的引入了常量:

use XXX\Driver\Driver;
...
if (class_exists(Driver::class)) {
    ...
}