使用继承健壮代码

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());

 

转载于:https://www.cnblogs.com/ohmydenzi/p/8939303.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值