之前說到每次新建一個對象,都會先執行__construct方法,那麼在繼承的時候,是否先執行父類的_construct方法,再執行子類__construct方法呢?
讓我們來做個實驗:
<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>
輸出結果如下:
child has constructed
說明在創建子類別的時沒有呼叫父類別的__construct方法,這是為什麼呢,原來這是用到php中的重寫(overwrite)這樣的機制,子類別的建構子實際上是覆蓋(override)了父類別的建構函數,這時執行的是該子類別的建構子。
那如果子類別不寫__construct方法會發生什麼事呢?讓我們來實驗一下:
<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>
;
輸出結果為:dd
說明父類別的__construct()沒有被繼承。
以上就介紹了php的學習筆記之面向對象(四)繼承補充,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。