Home > Article > Backend Development > Will PHP automatically instantiate the parent class when instantiating a subclass?
Paste the test code first
<code><?php class A { private $name = 'A'; public function setName($value) { $this->name = $value; echo $this->name; } } class B extends A { public function Name() { $this->setName('abc'); } } $b = new B(); $b->Name();</code>
The output result is abc. Will the parent class be automatically instantiated when instantiating the subclass? If it is not automatically instantiated, how can the $name of the parent class be assigned a value?
Paste the test code first
<code><?php class A { private $name = 'A'; public function setName($value) { $this->name = $value; echo $this->name; } } class B extends A { public function Name() { $this->setName('abc'); } } $b = new B(); $b->Name();</code>
The output result is abc. Will the parent class be automatically instantiated when instantiating the subclass? If it is not instantiated automatically, how can the $name of the parent class be assigned a value?
I object to the answer above with my real name.
Let’s talk about the conclusion first:
PHP will inherit all methods and attributes of the parent class when inheriting.
Due to permission control, private methods and properties of the parent class cannot be used in subclasses.
But using your own private properties in the parent class is not affected.
We modify the above code to look like this:
<code class="php"><?php class A { private $name = 'A'; public function setName($value) { $this->name = $value; } } class B extends A { public function Name() { var_dump($this); $this->setName('abc'); var_dump($this); } } $b = new B(); $b->Name(); </code>
Output results
<code class="php">class B#1 (1) { private $name => string(1) "A" } class B#1 (1) { private $name => string(3) "abc" }</code>
Clear at a glance.
It seems that class inheritance is not learned enough. Subclasses inherit all the inherited member properties and member methods of the parent class.
Calling $b->Name(); is to call the Name member method in the object instantiated by class B, and the setName method of the parent class is inherited. You can imagine that the setName method has been written in class B, so class B can directly use $this->setName to adjust.
Looking at your example again, we know that the private member properties and methods described by private in the parent class will not be inherited. Therefore, although the setName method exposed by the parent class is called in class B, the setName method is modified in the method. $this->name is actually just a new attribute, not the attribute assigned the value 'A' in the parent class.