小熊奶糖(BearCandy)
小熊奶糖(BearCandy)
发布于 2024-03-13 / 10 阅读
0
0

php 面向对象 类的多态

在PHP中,面向对象编程(OOP)中的多态(Polymorphism)是指允许一个接口被多个类实现,或者允许一个类派生出多个子类,且子类可以重写或扩展父类的方法,从而使同一类型的对象在不同情境下表现出不同的行为。

多态的定义主要包括以下要点:

  1. 接口实现(Interface Implementation):通过定义接口,不同的类可以实现同一个接口,意味着这些类都需要提供接口中声明的所有方法的具体实现。这样,即便这些类具有不同的内部结构,但只要实现了相同接口,就可以通过接口类型变量调用对应的方法,体现多态性。
interface Shape {
    public function area(): float;
}

class Circle implements Shape {
    private float $radius;

    public function __construct(float $radius) {
        $this->radius = $radius;
    }

    public function area(): float {
        return pi() * pow($this->radius, 2);
    }
}

class Square implements Shape {
    private float $side;

    public function __construct(float $side) {
        $this->side = $side;
    }

    public function area(): float {
        return $this->side * $this->side;
    }
}

function calculateArea(Shape $shape): float {
    return $shape->area();
}

$circle = new Circle(5);
$square = new Square(10);

echo calculateArea($circle); // 输出圆的面积
echo calculateArea($square); // 输出正方形的面积
  1. 继承与方法重写(Inheritance and Method Overriding):通过继承父类并重写父类中的方法,子类能够在保持父类公共接口的同时,赋予方法不同的实现,这也体现了多态性。
abstract class Animal {
    abstract public function makeSound(): string;
}

class Dog extends Animal {
    public function makeSound(): string {
        return "Woof!";
    }
}

class Cat extends Animal {
    public function makeSound(): string {
        return "Meow!";
    }
}

function animalSounds(Animal $animal) {
    echo $animal->makeSound();
}

$dog = new Dog();
$cat = new Cat();

animalSounds($dog); // 输出 "Woof!"
animalSounds($cat); // 输出 "Meow!"

在这个例子中,无论是通过接口还是继承的方式,都展示了多态的核心特性——通过一个通用的引用类型(接口或父类),调用的方法取决于实际的对象类型,从而达到灵活处理多种不同类对象的能力。


评论