如何通过子类设置/修改父类变量


How can I set/modify parent class variables through child class?

编辑:

对不起。我只是能够通过在我的子类调用中将父类传递为$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;

我想你对类如何工作感到困惑

parent::$amount = 50; // update the amount in parent

您不需要这样做,除非您在子类中重新定义$amount,并且您的父类只查找该值(即self::$amount(。你的孩子继承了所有不是private的东西,所以你可以直接使用

$this->amount = 50;