`

php5 读书心得(1)

阅读更多
由于工作中要用到PHP,最近下了本《PHP5 POWER PROGRAMMING》在读,外文的,还不错,打算写些读书心得,可能会零散些。这次讲的是多态。

    首先看一个例子,是讲动物发出的叫声的。
class Cat {
    function miau()
    {
        print "miau";
    }
}

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

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

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

    这里输出的是:
miau(猫的叫声)
wuff(狗的叫声)
     熟悉OOP的都知道,这个例子扩展性不好,因为如果你要加入更多动物的话,需要用很多个IF ELSE来判断,而且要重复写很多代码,有了多态后,就好办了。PHP5中终于有多态这东西了,多个子类可以扩展继承父类,上面的例子改写如下:
   class Animal {
    function makeSound()
    {
        print "Error: This method should be re-implemented in the children";
    }
}

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

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());
可以看出,这个时候,无论增加什么动物,printtherightsound方法是不需要 进行任何修改的了!当然,大家学过OOP的可以看出,这个例子可以进一步修改,就是将ANIMAL声明为抽象基类拉。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics