当前位置:网站首页>【PHP】php多态
【PHP】php多态
2022-06-22 21:24:00 【weixin_43224306】
多态的含义是:同一类的对象收到相同消息时,会得到不同的结果。而这个消息是不可预测的。多态,顾名思义,就是多种状态,也就是多种结果。
例1
<?php
class employee{
protected function working(){
echo '本方法需要重载';
}
}
class teacher extends employee{
public function working(){
echo '教书';
}
}
class coder extends employee{
public function working(){
echo '写代码';
}
}
function doprint($obj){
if(get_class($obj) == 'employee'){
echo 'Error';
}else{
$obj->working();
}
}
doprint(new teacher());
doprint(new coder());
doprint(new employee());
例2
<?php
interface employee{
public function working();
}
class teacher implements employee{
public function working(){
echo '教书';
}
}
class coder implements employee{
public function working(){
echo '写代码';
}
}
function doprint(employee $i){
$i->working();
}
$a = new teacher;
$b = new coder;
doprint($a);
doprint($b);
例2和例1没多少区别,不过代码中doprint函数的参数是一个接口类型的变量,符合“同一类型,不同结果”这一条件,具有多态性的一般特性,因此是多态
例1中如果把doprint函数的obj参数看做一种类型(把所有弱类型看做一种类型),那也可以认为是多态,否则不是
区别是否是多态的关键在于看对象是否属于同一类型
php中父类和子类看做“继父”和“继子”关系,它们存在继承关系,但是不存在血缘关系。因此子类无法向上转型为父类,从而失去多态最典型的特性
边栏推荐
- Is it safe to open a securities account by downloading the qiniu app? Is there a risk?
- 保证数据库和缓存的一致性
- canvas生成海报
- OJ每日一练——找第一个只出现一次的字符
- Digital data was invited to participate in Nantong enterprise digital transformation Seminar
- OJ daily practice - Verifying substring
- Problèmes rencontrés lors de l'utilisation de redistemplate
- 为什么现在大家都不用外键了(二)?
- 斐波那契数列合集
- 事物系统的几种异常场景
猜你喜欢

Tp5.1 upload excel file and read its contents

Learning the interpretable representation of quantum entanglement, the depth generation model can be directly applied to other physical systems

事务系统的隔离级别

wallys/WiFi6 MiniPCIe Module 2T2R 2 × 2.4GHz 2x5GHz

考过HCIP依然转行失败,职业网工最看重的到底是什么

口令安全是什么意思?等保2.0政策中口令安全标准条款有哪些?

Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!

canvas生成海报

After passing the hcip exam, I still failed to change my career. What do professional network workers value most

Enjoy high-performance computing! Here comes the Tianyi cloud HPC solution
随机推荐
如何使用enum数据类型
Sword finger offer 11 Minimum number of rotation array
Flutter outsourcing, undertaking flutter project
Anti shake & throttling enhanced version
Introduction to database access tools
事物系统的几种异常场景
企业数字化不是各自发展,而是全面SaaS化推进
A spark app demo
js图片分辨率压缩
保证数据库和缓存的一致性
为什么现在大家都不用外键了(二)?
Smart data won two annual awards at the second isig China Industrial Intelligence Conference
异步FIFO
剑指 Offer 07. 重建二叉树
Problèmes rencontrés lors de l'utilisation de redistemplate
os.Args[1:]中命令行参数为空时,不执行内部语句
在Word中自定义多级列表样式
OJ每日一练——病毒的增生
DML:Data Manipulation Language 数据操纵语言
OJ daily practice - Verifying substring