如何从命名空间PHP调用全局函数类 [英] how to call global functions classes from namespace PHP
问题描述
有什么方法可以避免使用如此频繁的反斜杠吗?
Is there any way how to avoid to using so often backslash ?
现在,如果我使用命名空间并在其中调用全局名称,则必须使用反斜杠:
Now if i'm using namespace and calling something global inside it i have to use backslash:
namespace foo;
$a = new \my\name(); // instantiates "my\name" class
echo \strlen('hi'); // calls function "strlen"
$a = \INI_ALL; // $a is set to the value of constant "INI_ALL"
在那种情况下,名称空间中的代码变得非常丑陋,有什么方法可以避免这种情况?
in that case code inside namespace become really ugly, is there any way how to avoid that situation ???
该示例取自以下网址: http://www. php.net/manual/en/language.namespaces.faq.php
The example was taken from that url: http://www.php.net/manual/en/language.namespaces.faq.php
但是我的问题是,如果我需要从命名空间中调用一些内置类,那么我必须在名称前使用反斜杠,我可以以某种方式避免它吗?
But my problem in that, if I need call some built in class from namespace i have to use backslash in front of the name, can I somehow avoid it ?
推荐答案
全局名称空间中的常量和函数不必加反斜杠. PHP将自己退回到全局名称空间. PHP手册中有一整章对此进行了解释:
constants and functions from the global namespace do not have to be prepended with a backslash. PHP will fallback to the global namespace for those on it's own. There is a whole chapter in the PHP manual explaining this:
在名称空间中,当PHP在类名称,函数或常量上下文中遇到不合格的名称时,它将以不同的优先级来解析这些名称.类名称始终解析为当前名称空间名称. […]对于函数和常量,如果没有命名空间的函数或常量,PHP将退回到全局函数或常量.
Inside a namespace, when PHP encounters a unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. […] For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.
这篇关于如何从命名空间PHP调用全局函数类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!