php多态

发布时间:2014-07-15 18:15:11 阅读:1225次
<?php
class Cat{
function miau(){
print "miau";
}
}

class Dog{
function wuff(){
print "wuff";
}
}

function printTheRightSound($obj){
if($obj instanceof Cat){
$obj->miau();
}elseif($obj instanceof Dog){
$obj->wuff();
}else{
print "Error:Passed wrong kind of object";
}
print "<br>";
}
printTheRightSound(new Cat());
printTheRightSound(new Dog());
printTheRightSound("test");



class Animal{
function makeSound(){
print "Error:This method should be re-implemented in the children";
}
}

class cats extends Animal{
function makesound(){
print "miau";
}
}

class Dogs extends Animal{
function makesound(){
print "wuff";
}
}


function printTheRightSounds($obj){
if($obj instanceof Animal){
$obj->makeSound();
}else{
print "Error:Passed wrong kind of object";
}
echo "<br>";
}
printTheRightSounds(new Cats());
printTheRightSounds(new Dogs());
printTheRightSounds("pigs");
?>

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询
上一篇:php抽象类
下一篇:php文件操作

转载请注明:php多态 出自老鄢博客 | 欢迎分享