Robust code using inheritance

OOP is not a simple collection of functions and data, but uses classes and inheritance to easily describe real-world situations. It can easily upgrade projects by inheriting and reusing code. So in order to write robust and scalable code, it is usually necessary to minimize the use of flow control statements (such as 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());

Use inheritance to optimize

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324813584&siteId=291194637