调用另一个名称空间中定义的不带前缀的PHP函数 [英] Calling a PHP function defined in another namespace without the prefix
问题描述
namespace foo {
function bar(){echo !FOO \\\
; }
class MyClass {}
}
调用时必须指定名称空间它来自另一个(或全局)命名空间:
bar(); //调用未定义的函数\bar()
foo\bar(); // ok
使用类可以使用use语句有效地将类导入到当前命名空间
use foo \ MyClass as MyClass;
new MyClass(); // ok,实例化foo \ MyClass
但这不适用于函数[如果有多少,那么就很笨拙]:
使用foo \ bar作为栏;
bar(); //调用未定义的函数\bar()
您可以使用命名空间来缩短前缀键入,
使用foo作为f; //更有用的,如果foo更长或嵌套
f \ bar(); // ok
但是有什么方法可以完全删除前缀吗?
背景:我正在研究Hamcrest匹配库,它定义了许多工厂函数,其中许多函数都被设计为嵌套。命名空间前缀确实会杀死表达式的可读性。比较
assertThat($ names,
is(anArray(
equalTo('Alice'),
startsWith('Bob'),
anything(),
hasLength(atLeast(12))
)));
至
使用Hamcrest作为h;
h\assertThat($ names,
h\is(h\anArray(
h\equalTo('Alice'),
h\startsWith('Bob')),
h \anything(),
h\hasLength(h\atLeast(12))
)));
PHP 5.6将允许使用使用
关键字:
namespace foo\bar {
function baz (){
echo'foo.bar.baz';
}
}
命名空间{
使用函数foo\bar\baz;
baz();
}
有关更多信息,请参阅RFC:https://wiki.php.net/rfc/use_function
When you define a function in a namespace,
namespace foo {
function bar() { echo "foo!\n"; }
class MyClass { }
}
you must specify the namespace when calling it from another (or global) namespace:
bar(); // call to undefined function \bar()
foo\bar(); // ok
With classes you can employ the "use" statement to effectively import a class into the current namespace [Edit: I thought you could "use foo" to get the classes, but apparently not.]
use foo\MyClass as MyClass;
new MyClass(); // ok, instantiates foo\MyClass
but this doesn't work with functions [and would be unwieldy given how many there are]:
use foo\bar as bar;
bar(); // call to undefined function \bar()
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
f\bar(); // ok
but is there any way to remove the prefix entirely?
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))
)));
to
use Hamcrest as h;
h\assertThat($names,
h\is(h\anArray(
h\equalTo('Alice'),
h\startsWith('Bob'),
h\anything(),
h\hasLength(h\atLeast(12))
)));
PHP 5.6 will allow to import functions with the use
keyword:
namespace foo\bar {
function baz() {
echo 'foo.bar.baz';
}
}
namespace {
use function foo\bar\baz;
baz();
}
See the RFC for more information: https://wiki.php.net/rfc/use_function
这篇关于调用另一个名称空间中定义的不带前缀的PHP函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!