Rumah  >  Artikel  >  pembangunan bahagian belakang  >  面向对象PHP(五)

面向对象PHP(五)

WBOY
WBOYasal
2016-07-29 09:16:16905semak imbas

<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></span></code>

版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了面向对象PHP(五),包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn