php多态

<?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");
?>

    A+
发布日期:2014年07月15日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: