路径根
文件:classA.php
class ClassA
{
public $returnA = null;
public $errorA = "Default error";
function __construct
{
$this -> func_A();
}
public function func_A()
{
require_once 'classB.php';
$obj = new ClassB;
$obj -> func_B();
}
}
文件:classB.php
class ClassB extends ClassA
{
public function func_B()
{
# attempt
$this -> errorA = "Error func_B";
}
}
文件:index.php
require_once 'ClassA.php';
$obj = new ClassA;
echo ($obj -> returnA != null) ? $obj -> returnA : $obj -> errorA;
我从index.php
返回的信息是:“默认错误”。
我期望的是:“错误func_B”。
errorA
的{{1}}属性没有变化?答案 0 :(得分:1)
您只得到默认字符串,因为func_A()
正在创建ClassB
的 new 实例,在其上调用一个函数,然后将其扔给您(因为您不是退还它。)
public function func_A()
{
require_once 'classB.php';
$obj = new ClassB; // New object instantiated
$obj -> func_B(); // Function called on $obj
// $obj dies here, as it is not returned and will go out of scope.
}
本质上,func_A()
在上面的代码中没有执行任何有价值的操作,因为它创建然后丢弃了一个对象。
作为一个适当的解决方案,我首先要问为什么您想将扩展类封装在基类中,因为如果此代码不只是理论上的代码,则可能会出错。例子。