tags:

views:

265

answers:

3
use MyNamespace;

class NonPersistentStorage implements StorageInterface

Both are in MyNamespace. Yet PHP looks for MyNamespace\NonPersistentStorage and StorageInterface (instead of MyNamespace\StorageInterface). Am I missing something?

A: 

Try using:

use MyNamespace;

class NonPersistentStorage implements MyNamespace\StorageInterface
RaYell
+2  A: 

Actually, that "use" declaration does absolutely nothing. You should import (use) namespaces when they are deeper in the namespace hierarchy (e.g. use Foo\Bar\Baz) or when you want to give them an alias (e.g. use Foo as Bar). I think you wanted to declare that the file itself belongs to MyNamespace:

namespace MyNamespace;

class NonPersistentStorage implements StorageInterface { /* ... */ }

Or, you may also want to import separate functions and classes, using the same syntax as for namespaces.

Ignas R
Argh, that was indeed the problem. I can laugh with it now was completely WTF for some time.
koen
+1  A: 

PHP Namespaces work a bit different than in other languages. When you import a namespace, you aren't really bringing classes into scope, you're just aliasing the namespace. Importing only one level of namespace does absolutely nothing. Even when you import something, you still need to reference its bottommost namespace.

For example, if you have this:

foo.php:

namespace Bar\Baz\Biz;

class Foo
{}

Here is how you use it:

blah.php:

use Bar\Baz\Biz;

$var=new Biz\Foo();

See how I still have to reference it using Biz, even though I imported it?

However, you can get around this using aliases: blah.php:

use Bar\Baz\Biz\Foo as Foo;

$var=new Foo();

As you can see, I no longer have to qualify it.

Unfortunately, however, there is no "import all" in PHP; if you want to do what's done above, you have to alias each and every class you want to import.

ryeguy