例1:
命名空间Inori \ Test;
类MainTest { }
例2:
命名空间Inori \ Test \ SubTest;
类SubTest扩展???? { }
问题:有没有办法在命名空间中快速升级,以便SubTest可以扩展MainTest?像"../MainTest"
之类的东西?还是我坚持使用\Inori\Test\MainTest
?
答案 0 :(得分:20)
不支持相对名称空间。但是有一个请求: https://bugs.php.net/bug.php?id=52504
如果您在文件顶部导入类,那么它应该不是那么重要。
namespace Inori\Test\SubTest;
use Inori\Test\MainTest;
class SubTest extends MainTest { }
答案 1 :(得分:1)
看到已经提供了已接受的答案。但是,您可以使用这些代码来利用相对名称空间(注意:您可以免费使用下面的代码免费并在代码中引用作者,不需要作者提供任何保证,代码的使用风险自负)。
update:代码可以在您的类中使用,通过相对名称空间动态地快速加载其他类。本主题的第一部分是寻找一种通过相对命名空间将类扩展到其他类的方法,这种代码仍然不可能。
在您的课程中,只需添加以下代码:
public function TestRelativeNamespace()
{
// (e.g., param1 = site\lib\firm\package\foo, param2 = .\..\..\different)
$namespace = $this->GetFullNamespace(__NAMESPACE__, '.\\..\\..\\different');
// will print namespace: site\lib\firm\different
print $namespace;
// to create object
$className = $namespace . '\\TestClass';
$test = new $className();
}
public function GetFullNamespace($currentNamespace, $relativeNamespace)
{
// correct relative namespace
$relativeNamespace = preg_replace('#/#Di', '\\', $relativeNamespace);
// create namespace parts
$namespaceParts = explode('\\', $currentNamespace);
// create parts for relative namespace
$relativeParts = explode('\\', $relativeNamespace);
$part;
for($i=0; $i<count($relativeParts); $i++) {
$part = $relativeParts[$i];
// check if just a dot
if($part == '.') {
// just a dot - do nothing
continue;
}
// check if two dots
elseif($part == '..') {
// two dots - remove namespace part at end of the list
if(count($namespaceParts) > 0) {
// remove part at end of list
unset($namespaceParts[count($namespaceParts)-1]);
// update array-indexes
$namespaceParts = array_values($namespaceParts);
}
}
else {
// add namespace part
$namespaceParts[] = $part;
}
}
if(count($namespaceParts) > 0) {
return implode('\\', $namespaceParts);
}
else {
return '';
}
}