有什么办法可以避免经常使用反斜杠吗?
现在,如果我使用命名空间并在其中调用全局的东西,我必须使用反斜杠:
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"
在那种情况下,命名空间内的代码变得非常丑陋,有什么办法可以避免这种情况???
示例取自该网址:http://www.php.net/manual/en/language.namespaces.faq.php
但我的问题在于,如果我需要从命名空间调用一些内置类,我必须在名称前面使用反斜杠,我能以某种方式避免它吗?
最佳答案
全局命名空间中的常量和函数不必在前面加上反斜杠。 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 - 如何从命名空间 PHP 调用全局函数类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12157238/