原则上讲,构造函数的继承没有太大的意义,节省的是代码的重写,而不是方法的声明,也就是说,在父类中声明的构造函数必须再在子类中声明一次,其实,这也是一个重写的过程。
PHP的构造函数继承必须满足以下条件:
1、当父类有构造函数的声明时,子类也必须有声明,否则会出错。
2、在执行父类的构造函数时,必须在子类中引用parent关键字。
下面是正确的使用方法演示:
1 2 3 4 5 6 7 8 9 10 11 |
abstract <span style="color: #000000;font-weight: bold">class</span> admin<span style="color: #009900">{</span><span style="color: #666666;font-style: italic">//父类</span> <span style="color: #000000;font-weight: bold">public</span> <span style="color: #000000;font-weight: bold">function</span> __construct<span style="color: #009900">(</span><span style="color: #009900">)</span><span style="color: #009900">{</span> <span style="color: #b1b100">echo</span> <span style="color: #0000ff">"www.chhua.com"</span><span style="color: #339933">;</span> <span style="color: #009900">}</span> <span style="color: #009900">}</span> <span style="color: #000000;font-weight: bold">class</span> adminIndex <span style="color: #000000;font-weight: bold">extends</span> admin<span style="color: #009900">{</span><span style="color: #666666;font-style: italic">//子类</span> <span style="color: #000000;font-weight: bold">public</span> <span style="color: #000000;font-weight: bold">function</span> __construct<span style="color: #009900">(</span><span style="color: #009900">)</span><span style="color: #009900">{</span> parent<span style="color: #339933">::</span>__construct<span style="color: #009900">(</span><span style="color: #009900">)</span><span style="color: #339933">;</span> <span style="color: #009900">}</span> <span style="color: #009900">}</span> |