修改
对不起我只能通过在子类调用中将父类作为$ this传递来做我想要做的事情。 $load = new Child_Class( $this );
非常确定它看起来有点难看,但却符合我的目的
所以基本的想法是我正在写一个有一些变量的父类,例如。
class Parent_Class {
public $amount = 0;
public $user_id = 0;
public function __construct() {
// I load the child to do some work and update amount.
$load = new Child_Class();
}
}
然后我有一个儿童班。我正在尝试从子类中更新Parent类$ amount变量,但是从父类变量访问它。
class Child_Class extends Parent_Class {
public function __construct() {
// How can I do this?
parent::$amount = 50; // update the amount in parent
}
}
问题是我正在尝试访问这样的数据:
$parent = new Parent_Class();
$amount = $parent->amount;
但这不起作用,只有$parent::$amount
(静态)有效。有没有办法让它作为非静态变量工作?
所以我的父类是从:
开始的$parent = new Parent_Class();
我在子课上做了一些工作,需要通过
返回更新的金额$parent->amount;
答案 0 :(得分:2)
我认为你对课程的运作方式感到困惑
parent::$amount = 50; // update the amount in parent
除非您在孩子中重新声明$amount
,否则您不需要这样做,而您的父级只会查找自己的值(即self::$amount
)。您的孩子继承了不是private
的所有内容,因此您可以使用
$this->amount = 50;