First paste the test code {code...} and the output result is abc. Will the parent class be automatically instantiated when the subclass is instantiated? If it is not automatically instantiated, how can the $ name of the parent class be assigned a value? First paste the test code
name = $value; echo $this->name; }}class B extends A{ public function Name() { $this->setName('abc'); }}$b = new B();$b->Name();
The output result is abc. Will the parent class be automatically instantiated when the subclass is instantiated? If it is not automatically instantiated, how can the $ name of the parent class be assigned a value?
Reply content:
First paste the test code
name = $value; echo $this->name; }}class B extends A{ public function Name() { $this->setName('abc'); }}$b = new B();$b->Name();
The output result is abc. Will the parent class be automatically instantiated when the subclass is instantiated? If it is not automatically instantiated, how can the $ name of the parent class be assigned a value?
Real-name objection to answers upstairs.
Conclusion:
-
Php inherits all the methods and attributes of the parent class.
-
Because of permission control, the private methods and attributes of the parent class cannot be used in subclass.
-
However, using your own private attributes in the parent class is not affected.
Proof
Modify the code as follows:
name = $value; }}class B extends A{ public function Name() { var_dump($this); $this->setName('abc'); var_dump($this); }}$b = new B();$b->Name();
Output result
class B#1 (1) { private $name => string(1) "A"}class B#1 (1) { private $name => string(3) "abc"}
Clear at a glance.
It seems that the inheritance of classes is not enough. subclass inherits all member attributes and member methods that can be inherited by 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 use $ this-> setName to call it directly.
Looking at your example, we know that the attributes and methods of private members described in the parent class will not be inherited. Therefore, although the setName method exposed by the parent class is called in Class B, however, the $ this-> name modified in the method is actually A new attribute, rather than being assigned the 'A' attribute in the parent class.