Maison >développement back-end >tutoriel php >php的学习笔记之面向对象(四)继承补充
之前说到每次新建一个对象,都会先执行__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教程有兴趣的朋友有所帮助。