Ahmed Elmahdy Ahmed Elmahdy - 1 year ago 84
PHP Question

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


I am sorry. I was just able to do what I am trying to do by passing the parent class as $this in my child class call.

$load = new Child_Class( $this );
pretty sure it looks a bit ugly but serves my purpose

So the basic idea is that I am writing a parent class that has some variables e.g.

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();


And then I have a child class. I'm trying to update the Parent class $amount variable from within child class yet access it from parent class variable.

class Child_Class extends Parent_Class {

public function __construct() {

// How can I do this?
parent::$amount = 50; // update the amount in parent


The problem is that I am trying to access the data like this:

$parent = new Parent_Class();
$amount = $parent->amount;

But this does not work and only
(static) works. Is there a way to make it work as non-static variable?

SO my parent class was initated from:

$parent = new Parent_Class();

I make some work in child class and need to return updated amount via


Answer Source

I think you're confused about how classes work

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

You don't need to do that unless you're redeclaring $amount in your child AND your parent class only looks to itself for that value (i.e. self::$amount). Your child inherits everything that isn't private so you can just use

$this->amount = 50;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download