首頁  >  文章  >  後端開發  >  物件導向PHP(五)

物件導向PHP(五)

WBOY
WBOY原創
2016-07-29 09:16:16905瀏覽

<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(五),包括了方面的內容,希望對PHP教程有興趣的朋友有幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn