Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example of polymorphic code implemented by PHP

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

这篇文章主要讲解了"PHP实现多态代码实例",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"PHP实现多态代码实例"吧!

多态定义:只关心一个接口或者基类,而不关心一个对象的具体类。(同一类型,不同结果)

这里两个例子:

第一个,我们发现,基类定义了标准,子类进行了自我规则的实现。这是多态的一个要求。同时,这是满足重写;实际上这是不同类的不同表现;没有严格满足一个接口,或者基类编程。因为你调用的时候不是 stu->showGrade() 而是各自自己的方法;

class stu{ public function showGrade(){ echo "base class"; }}class xiaomin extends stu{ public function showGrade(){ echo "is son show 80"; } }class xiaoli extends stu{ public function showGrade(){ echo "is son show 60"; } }function doit($obj){ if(get_class($obj) != "stu"){ $obj->showGrade(); }}doit(new xiaoli());doit(new xiaomin());

第二个例子:dovoice 参数规定了$obj 为animal,意识就是用接口 接受了 实现类对象。了向上转型。这就符合同一类型,不同结果了,这就是多态;

实际上在Java中 会是 animal a = new dog();这样子的;因为PHP 是若类型语言。没有对象转型机制。

interface animal{ public function voice();}class cat implements animal{ public function voice(){ echo "miao~~~

"; }}class dog implements animal{ public function voice(){ echo "wang ~~~

"; }}function dovoice(animal $obj){ $obj->voice();}dovoice(new dog());dovoice(new cat());感谢各位的阅读,以上就是"PHP实现多态代码实例"的内容了,经过本文的学习后,相信大家对PHP实现多态代码实例这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report