Question

I'm not sure if this is even possible but here goes. I want to set the value of a protected variable from within a child class and then access that value from the parent class. This is what I have tried:

class A {
    protected $a;

    public function __construct() {
        new B;

        echo "Parent Value: {$this->a}";
    }

    protected function setter($value) {
        $this->a = $value;
    }
}

class B extends A {
    public function __construct() {
        $this->setter('set value');

        echo "Child Value: {$this->a}<br />";
    }
}


new A;

I'm expecting the output for the above code to be:

Child Value: set value
Parent Value: set value

However I get the following instead:

Child Value: set value
Parent Value:

Is it possible to set the value of a protected variable from within a child class and then access that value in the parent class? If not how would I accomplish this?

Was it helpful?

Solution

You can set the value and access it from the child class without any problems - you are actually doing that when you generate your B-class object in the A-class constructor - but the problem with your code is that you are generating a parent object and in the constructor of that parent object you generate a new object of the child class.

So what is happening is:

  • You generate an A object, the constructor of the A class runs;
  • In the constructor you generate a B object. This is a new object, unrelated to your current A object;
  • The constructor of the B object you set the value and echo it (basically answering your own question), the first line of your output is as expected;
  • Continuing in the constructor of the A object, you discard the generated B-class object and echo the value of $this->a but that value is not set for that object, so you get nothing.

I am kind of confused why you would want to construct a child object in the constructor of the parent. Normally I would construct a B object and in the constructor of that object, first call the parent constructor before doing B-specific stuff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top