使用继承健壮代码

OOP不是简单的把函数和数据简单集合起来,而是使用类和继承轻松的描述现实中的情况。它可以通过继承复用代码,轻松升级项目。所以为了写出健壮可扩展的代码,通常需要尽量减少使用流程控制语句(比如if)

<?php

class Cat {
    function miao(){
        print "miao";
    }
}

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

function printTheRightSound($obj)
{
    if ($obj instanceof cat) {
        $obj->miao();
    } elseif ($obj instanceof dog) {
        $obj->wuff();
    }
}

printTheRightSound(new Cat());
printTheRightSound(new Dog());

使用继承来优化

<?php


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

class Cat extends Animal {
    function makeSound(){
        print "miao";
    }
}

class Dog extends Animal{
    function makeSound(){
        print "wuff";
    }
}

function printTheRightSound($obj){
    if ($obj instanceof Animal) {
        $obj->makeSound();
    } else{
        print "Error:Passed wrong kind of object";
    }
    print "\n";
}

printTheRightSound(new Cat());
printTheRightSound(new Dog());

 

posted @ 2018-04-25 07:42  ohmydenzi  阅读(119)  评论(0编辑  收藏  举报