二、三大核心特征-多态

多态指的是面向对象编程时,屏蔽了子类对象之间的差异,可以使调用对象方法的客户端代码中代码保持通用性,而不必针对每个不同的对象写不同的实现。

多态的实现依靠的是继承、抽象方法或接口的特性。

例如:

//父类是一个抽象类Animal
abstract class Animal 
{
    abstract public function talk();
}

//子类Dog
class Dog extends Animal
{
    public function talk()
    {
        echo '新年旺旺';
    }
}

//子类Cat
class Cat extends Animal
{
    public function talk()
    {
        echo '喵喵';
    }
}

//客户端类Person
class Person
{    
    public function __construct()
    {
        $cat = new Cat();
        $dog = new Dog();
        $this->touchHead($cat);//输出:喵喵
        $this->touchHead($dog);//输出:新年旺旺
    }
    //摸动物的头,动物就会叫
    public function touchHead(Animal $animal) 
{
$animal->talk();
}
}

在touchHead方法中,我们无需知道具体的是哪个对象,只要这个对象是派生于动物父类,就可以调用talk方法。这种特性就是多态。

原文地址:https://www.cnblogs.com/mysic/p/8451232.html