简体   繁体   中英

How to call PHP a class from parent namespace?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM