调用在另一个命名空间中定义的 PHP 函数,不带前缀

2022-01-14 00:00:00 function namespaces 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

相关文章