gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:22:50 32 4
gpt4 key购买 nike

编辑:

对不起。通过在我的子类调用中将父类作为 $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();
}

}

然后我有一个子类。我正在尝试从子类中更新父类 $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();

我在 child 类做了一些工作,需要通过以下方式返回更新的金额

$parent->amount;

最佳答案

我认为你对类的工作方式感到困惑

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

你不需要这样做,除非你在你的 child 中重新声明 $amount 并且你的父类只查找自己的值(即 self::$amount)。您的 child 继承了所有非私有(private)的东西,因此您可以使用

$this->amount = 50;

关于php - 如何通过子类设置/修改父类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39552413/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com