当前位置:网站首页>【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中父类和子类看做“继父”和“继子”关系,它们存在继承关系,但是不存在血缘关系。因此子类无法向上转型为父类,从而失去多态最典型的特性
边栏推荐
- [STM32 skill] use the hardware I2C of STM32 Hal library to drive rx8025t real-time clock chip
- 10 Super VIM plug-ins, I can't put them down
- Leakcanary source code (2)
- C language greedy snake
- Introduction to database access tools
- 阻止别人使用浏览器调试
- C sqlsugar, hisql, FreeSQL ORM framework all-round performance test vs. sqlserver performance test
- [kubernetes series] overview of kubernetes
- OJ每日一练——跨越2020
- OJ每日一练—— 班级就餐
猜你喜欢

Freshman girls' nonsense programming is popular! Those who understand programming are tied with Q after reading

保证数据库和缓存的一致性

Ensure database and cache consistency

c# sqlsugar,hisql,freesql orm框架全方位性能测试对比 sqlserver 性能测试

程序员接私活兼职选择

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

OJ daily practice - spanning 2020

mysql主从同步及其分库分表基本流程

Customize multi-level list styles in word

OJ daily practice - filter extra spaces
随机推荐
Safe and reliable! Tianyi cloud data security management platform passed the evaluation
Is it difficult to turn weak current into professional network worker? Huawei pre-sales engineers share their own experience
OJ每日一练——整理命名
Digital data was invited to participate in Nantong enterprise digital transformation Seminar
SqlServer 复制表的自增属性
mysql主从同步及其分库分表基本流程
Canvas generate Poster
剑指 Offer 06. 从尾到头打印链表
多种方案实现图片的懒加载
Dip1000,1 of D
Use the find command
在一条DML语句中插入/更新/删除/获取几百万行数据,你会特别注意什么?
js图片分辨率压缩
'dare not doubt the code, but have to doubt the code 'a network request timeout analysis
阻止别人使用浏览器调试
OJ每日一练—— 班级就餐
OJ daily practice - word length
Unity: use ray to detect objects
Is it safe to open a securities account by downloading the qiniu app? Is there a risk?
js----SVG转PNG