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 函数,不带前缀
基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
