php 如何检查php中命名空间的存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18337650/
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 17:21:33  来源:igfitidea点击:

How to check the existence of a namespace in php

phpclassnamespacesexists

提问by Maxim Seshuk

I have a php libraryhttps://github.com/tedivm/Fetchand it uses Fetch namespace and I would like to check its existence in my script.

我有一个php 库https://github.com/tedivm/Fetch,它使用 Fetch 命名空间,我想检查它在我的脚本中的存在。

My script code:

我的脚本代码:

// Load Fetch
spl_autoload_register(function ($class) {
    $file = __DIR__ . '/vendor/' . strtr($class, '\', '/') . '.php';
    if (file_exists($file)) {
        require $file;

        return true;
    }
});

if (!class_exists('\Fetch')) {
  exit('Failed to load the library: Fetch');
}
$mail = new \Fetch\Server($server, $port);

but this message is always displayed. But the library is fully working.

但始终显示此消息。但图书馆正在全面运作。

Thanks in advance for any help!

在此先感谢您的帮助!

回答by ars265

You need to use the entire namespace in the class_existsI believe. So something like:

class_exists我相信您需要使用整个命名空间。所以像:

class_exists('Fetch\Server')

回答by George Steel

You can't check directly for the existence of a particular namespace, i.e. you'd have to class_exists('Fetch\\SomeClass'). See this question too: is it possible to get list of defined namespaces

您不能直接检查特定名称空间是否存在,即您必须检查class_exists('Fetch\\SomeClass')。也请参阅此问题:是否可以获取已定义名称空间的列表

回答by XedinUnknown

As George Steelwrote, it is impossible to check for a namespace. This is because a namespace is not something that exists; only structures exist within namespaces. See below example:

正如George Steel所写,不可能检查命名空间。这是因为命名空间不是存在的东西;只有结构存在于命名空间中。见下面的例子:

namespace Foo;

class Bar {
}

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