<code><span><span><?php</span><span>/** * 当接口中的某些方法对于所有的实现类都是一样的实现方法,只有部分方法需要用到多态的特性 * 人和动物吃东西不一样,呼吸一样 */</span> header(<span>"Content-Type: text/html; charset=utf-8"</span>);<span>//去除中文乱码</span><span>//abstract关键字定义抽象类</span><span>abstract</span><span><span>class</span><span>ACanEat</span>{</span><span>//在抽象方法前面加abstract关键字可以标明这个方法是抽象方法不需要具体的实现</span><span>abstract</span><span>public</span><span><span>function</span><span>eat</span><span>(<span>$food</span>)</span>;</span><span>//抽象类中可以包含普通的方法,有方法的实现</span><span>public</span><span><span>function</span><span>breath</span><span>()</span>{</span><span>echo</span><span>"Breath use the air.<br/>"</span>; } } <span>//继承抽象类用extends</span><span><span>class</span><span>Human</span><span>extends</span><span>ACanEat</span>{</span><span>//定义抽象类的子类需要对父类中的抽象方法定义</span><span>public</span><span><span>function</span><span>eat</span><span>(<span>$food</span>)</span>{</span><span>echo</span><span>"Human eating "</span>.<span>$food</span>.<span>"<br/>"</span>; } } <span><span>class</span><span>Animal</span><span>extends</span><span>ACanEat</span>{</span><span>public</span><span><span>function</span><span>eat</span><span>(<span>$food</span>)</span>{</span><span>echo</span><span>"Animal eating "</span>.<span>$food</span>.<span>"<br/>"</span>; } } <span>$pzy</span>=<span>new</span> Human(); <span>$dog</span>=<span>new</span> Animal(); <span>$pzy</span>->eat(<span>"肉"</span>); <span>$dog</span>->eat(<span>"骨头"</span>); <span>$pzy</span>->breath(); <span>$dog</span>->breath(); <span>?></span></span></code>
Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.
The above introduces object-oriented PHP (5), including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.