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 theA
class runs; - In the constructor you generate a
B
object. This is a new object, unrelated to your currentA
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 generatedB
-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.