9

I have the following namespace structure with the following class files

Application
|->App.php
|->Top
   |->Start.php
   |->Process.php
   |->Child
      |->Plugin.php

So in App.php I've declared

namespace Application;

in Startp.php declared

namespace Application\Top;

in Plugin.php declared

namespace Application\Top\Child;

I see that I can call the Plugin.php class from the App.php like

$object = new Top\Child\Plugin();

if it's a child/grandchild namespace, but what if I want to call Process.php from Plugin.php, which is the parent namespace from the branch? Is there something like double dots ".." to indicate the upper parent directory in namespace? I am trying to call something like

File: Plugin.php

$object = new ..\Process();

it didn't work, it looks like I can only start all the way from the root like

$object = new \Application\Top\Process()

Is this the only option? Thank you!

3
  • Have you tried "usings": use Application\Top; and then call $object = new Child\Process(); Commented Dec 13, 2013 at 4:06
  • @Saul Thank you for the answer, but I already know that, I am trying to find out if there is an shorter way to call a class that resides right above the parent level from a child level Commented Dec 13, 2013 at 4:08
  • I see. I've never thought that, haha. I'm used to put my "usings" at the top, even a namespace above. Commented Dec 13, 2013 at 4:11

1 Answer 1

13

As it mentioned here http://www.php.net/manual/en/language.namespaces.basics.php (in comments) there is only one way to specify namespaces - from root. You can not use ..\ to shorten namespace calls. To shorten calls in you code you can use

use \Application\Top\Process as SomeProcess;

and use, first at your code

$object = new SomeProcess();

Also you can write your class loader. To call $object = new ..\Process(); Here is the sketch:

$classPath = explode("\\", __NAMESPACE__);
array_pop($classPath);
$newClassPath = implode("\\", $classPath) . '\\'. 'Process';
$object = new $newClassPath();

Be sure to use double backslash when you want to use them in single quotes.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, actually I have read all those, it's just amazes me that namespace isn't flexible as I thought, so just to confirm if I haven't missing something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.