See the comment inside ChildEntity ::__construct()
:
class ChildEntity extends ParentEntity { /** @var int */ protected $ classParameter; function __construct(int $ classParameter) { /** * Question * * Below are the two ways of initializing the variable of ChildEntity * * Are they both initializing the same child(?) variable? * Are they initializing the parent(?) variable? * Can the child and parent have different values at the same time, * perhaps in different contexts? */ $ this->classParameter = $ classParameter; // init local(?) variable? parent::__construct($ classParameter); // init parent(?) variable? } } class ParentEntity { /** @var int */ protected $ classParameter; function __construct(int $ classParameter) { $ this->classParameter = $ classParameter; } } $ childEntity = new ChildEntity(100);
Why does the below work (slightly different code – parameter removed in parent, and child uses only parent constructor to initialize). It looks like the parent class manipulates a variable found in the child class, without that variable being present in parent. It is as if the variable in ChildEntity
and ParentEntity
become one, and the child and parent instances also serve as a single instance, for all intents and purposes. Is that what actually happens behind the scenes?
class ChildEntity extends ParentEntity { /** @var int */ protected $ classParameter; function __construct(int $ classParameter) { parent::__construct($ classParameter); print $ this->classParameter; } } class ParentEntity { function __construct(int $ classParameter) { $ this->classParameter = $ classParameter; } } $ childEntity = new ChildEntity(5);