It was mentioned before that every time a new object is created, the __construct method will be executed first. So when inheriting, should the _construct method of the parent class be executed first, and then the __construct method of the subclass be executed?
Let’s do an experiment:
<code><span><span>class</span><span>Father</span>{</span><span>public</span><span><span>function</span><span>__construct</span><span>()</span>{</span><span>echo</span><span>"father has constructed"</span>; } } <span><span>class</span><span>Child</span>{</span><span>public</span><span><span>function</span><span>__construct</span><span>()</span>{</span><span>echo</span><span>"child has constructed"</span>; } } <span>$c</span> = <span>new</span> Child(); </code>
The output results are as follows:
child has constructed
It shows that the __construct method of the parent class is not called when creating the subclass. Why is this? It turns out that this is using the overwrite mechanism in PHP. The constructor of the subclass is actually an override. The constructor of the parent class is executed, and the constructor of the subclass is executed.
So what will happen if the subclass does not write the __construct method? Let’s experiment:
<code><span><span>class</span><span>Father</span>{</span><span>public</span><span><span>function</span><span>__construct</span><span>()</span>{</span><span>echo</span><span>"father has constructed"</span>; } } <span><span>class</span><span>Child</span>{</span><span>public</span><span><span>function</span><span>show</span><span>()</span>{</span><span>echo</span><span>"dd"</span>; } } <span>$c</span> = <span>new</span> Child(); <span>$c</span>->show(); 输出结果为:dd</code>
;
The output result is: dd
It means that the __construct() of the parent class is not inherited.
The above introduces the object-oriented (4) inheritance supplement of PHP study notes, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.