<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>
저작권: 이 글은 블로거의 원본 글이므로 블로거의 허락 없이 복제할 수 없습니다.
위 내용은 객체지향 PHP(5)에 대한 내용을 포함하여 PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.