Php – Calling a PHP function defined in another namespace without the prefix

functionnamespacesPHP

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))
    )));

Best Answer

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