这篇文章是由于某些困难,我正在从第二个命名空间扩展第一个命名空间中定义的类。基于这篇文章:
PHP how to import all classes from another namespace
我试过了:
文件NameSpace1:
<?php
namespace FirstNS;
class baseObject
{
public $baseVar = 1;
public function baseFun() {}
}
?>
文件NameSpace2:
<?php
namespace SecondNS;
use FirstNS;
class extendedObject extends FirstNS\baseObject {
public $extendedVar = 1;
public function extendedFun() {
}
}
?>
但$this
中的extendedFun
只能访问$extendedVar
和extendedFun
,而不是$baseVar
和baseFun
。我还尝试了use FirstNS as ClassFromFirstNS;
和class extendedObject extends ClassFromFirstNS
,但$baseVar
和baseFun
仍无法通过$this
访问。 http://www.php.net/manual/en/language.namespaces.rationale.php,http://www.php.net/manual/en/language.namespaces.definition.php和http://www.php.net/manual/en/language.namespaces.importing.php上的信息似乎也没有直接解决此案例。
答案 0 :(得分:1)
我没有问题让你的代码工作,从你的问题中你不清楚你有什么问题:
namespace FirstNS
{
class baseObject
{
public $baseVar = 1;
public function baseFun() {}
}
}
namespace SecondNS
{
use FirstNS;
class extendedObject extends FirstNS\baseObject
{
public $extendedVar = 1;
public function extendedFun()
{
echo $this->extendedVar, "\n"; # works
$this->baseFun(); # works
}
}
echo '<pre>';
$obj = new extendedObject();
echo $obj->baseVar, "\n"; # works
$obj->extendedFun();
}
Demo - 希望这有用。
答案 1 :(得分:0)
试一试:
// File1.php
namespace FirstNS;
class baseObject
{
public $baseVar = 1;
public function baseFun() {}
}
// File2.php
namespace SecondNS;
include 'File1.php';
use FirstNS;
class extendedObject extends FirstNS\baseObject {
public $extendedVar = 2;
public function extendedFun()
{
var_dump($this->baseVar); // Outputs 1
var_dump($this->extendedVar); // Outputs 2
}
}
// File3.php
include 'File2.php';
$object = new SecondNS\extendedObject();
$object->extendedFun();