views:

68

answers:

1

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

I don't know an elegant solution, but...

You can create wrapper functions that encapsulate the functions in the external namespace. This will let you keep your code readability...

function assertThat($x, $y) { return h\assertThat($x, $y); }

Borealid
The existing functions are already convenience wrappers that call the real static factory methods. I could provide a duplicate copy of this module without the namespace and let the user decide which they wanted to import. The effect would be the same and I'd bet fairly easy to automate.
David Harkness