且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-19 23:18:40

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

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