Example1:
命名空间Inori\Test;
类MainTest {}
Example2:
命名空间Inori\测试\子测试;
类SubTest扩展?{}
问:有没有一种方法可以在名称空间中快速提升一个级别,以便SubTest可以扩展MainTest?像"../MainTest"
这样的?或者我被\Inori\Test\MainTest
卡住了
发布于 2011-08-30 23:44:36
不支持相对命名空间。不过,还是有这样的请求:https://bugs.php.net/bug.php?id=52504
如果你在文件的顶部导入你的类,这应该不是什么大问题。
namespace Inori\Test\SubTest;
use Inori\Test\MainTest;
class SubTest extends MainTest { }
发布于 2013-02-14 00:58:29
确保已经提供了可接受的答案。然而,在此,您可以使用代码来利用相对名称空间(注意:您可以免费使用下面的代码,并且不需要在代码中引用作者,作者不提供任何保证,使用代码的风险自负)。
更新:可以在类中使用代码,通过相对命名空间动态、快速地加载其他类。本主题的起始者正在寻找一种方法,通过相对命名空间将类扩展到其他类,这在本代码中也是不可能的。
只需在您的类中添加以下代码:
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 '';
}
}
https://stackoverflow.com/questions/7245695
复制相似问题