Calling a PHP function defined in another namespace without the prefix(调用在另一个命名空间中定义的 PHP 函数,不带前缀)
问题描述
在命名空间中定义函数时,
When you define a function in a namespace,
namespace foo {
    function bar() { echo "foo!
"; }
    class MyClass { }
}
从另一个(或全局)命名空间调用时必须指定命名空间:
you must specify the namespace when calling it from another (or global) namespace:
bar();          // call to undefined function ar()
fooar();      // ok
对于类,您可以使用use"语句将类有效地导入当前命名空间
With classes you can employ the "use" statement to effectively import a class into the current namespace
use fooMyClass as MyClass;
new MyClass();  // ok, instantiates fooMyClass
但这不适用于函数[并且考虑到函数的数量会很笨拙]:
but this doesn't work with functions [and would be unwieldy given how many there are]:
use fooar as bar;
bar();          // call to undefined function ar()
你可以给命名空间起别名,使前缀更短,
You can alias the namespace to make the prefix shorter to type,
use foo as f;   // more useful if "foo" were much longer or nested
far();        // ok
但是有什么办法可以完全去掉前缀呢?
but is there any way to remove the prefix entirely?
背景:我正在研究 Hamcrest 匹配库,该库定义了许多工厂函数,其中许多被设计为嵌套.拥有命名空间前缀确实会破坏表达式的可读性.比较
Background: I'm working on the Hamcrest matching library which defines a lot of factory functions, and many of them are designed to be nested. Having the namespace prefix really kills the readability of the expressions. Compare
assertThat($names, 
    is(anArray(
        equalTo('Alice'), 
        startsWith('Bob'), 
        anything(), 
        hasLength(atLeast(12))
    )));
到
use Hamcrest as h;
hassertThat($names, 
    his(hanArray(
        hequalTo('Alice'), 
        hstartsWith('Bob'), 
        hanything(), 
        hhasLength(hatLeast(12))
    )));
推荐答案
PHP 5.6 将允许使用 use 关键字导入函数:
PHP 5.6 will allow to import functions with the use keyword:
namespace fooar {
    function baz() {
        echo 'foo.bar.baz';
    }
}
namespace {
    use function fooaraz;
    baz();
}
有关详细信息,请参阅 RFC:https://wiki.php.net/rfc/use_function
See the RFC for more information: https://wiki.php.net/rfc/use_function
这篇关于调用在另一个命名空间中定义的 PHP 函数,不带前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:调用在另一个命名空间中定义的 PHP 函数,不带前缀
				
        
 
            
        - 如何定位 php.ini 文件 (xampp) 2022-01-01
 - Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
 - SoapClient 设置自定义 HTTP Header 2021-01-01
 - 正确分离 PHP 中的逻辑/样式 2021-01-01
 - 从 PHP 中的输入表单获取日期 2022-01-01
 - 没有作曲家的 PSR4 自动加载 2022-01-01
 - PHP Count 布尔数组中真值的数量 2021-01-01
 - Mod使用GET变量将子域重写为PHP 2021-01-01
 - 带有通配符的 Laravel 验证器 2021-01-01
 - Laravel 仓库 2022-01-01
 
				
				
				
				