user1615069
user1615069

Reputation: 633

Relative nested namespaces in PHP

I'll try to describe the situation I'm having problems with:

I have one main folder. I keep all files in there (empty classes for a reason), and one sub-folder, containing the same files, with all implementations here (empty classes extend them).

the main folder's namespace is declared as Project/Folder, and the sub-folder as Project/Folder/Subfolder. These are class's declarations:

namespace Project\Folder;
class Foo extends Subfolder\Foo {  }

namespace Project\Folder\Subfolder;
class Foo {  }

What I want to achieve is to be able to call other classes from inside of the Project\Folder\Subfolder\Foo through these empty classes on the lower level, with only its name, e.g.:

namespace Project\Folder\Subfolder;
class Foo {
     function bar() {
        Another_Class::do_something();
     }
}

By default, there will be called Another_Class from the Project\Folder\Subfolder namespace. I want this to refer to Another_Class from the Project\Folder namespace with the same syntax - is that possible?

I hope I explained this clear enough, if not, write a commend, and I'll try to make it clearer.

Upvotes: 0

Views: 2969

Answers (1)

Yes Barry
Yes Barry

Reputation: 9856

You can achieve that using the use statement.

use Project\Folder\Subfolder\Another_Class as SomeAlias;

// ...

SomeAlias::doSomething();

// or

$object = new SomeAlias();
$object->doSomething();

Alternatively, you would have to reference the entire namespace:

\Project\Folder\Subfolder\Another_Class::doSomething();

// or

$object = new \Project\Folder\Subfolder\Another_Class();
$object->doSomething();

More information here.

Upvotes: 2

Related Questions