php 实现多态
多态的概念
多态是面向对象编程的三大特性之一(封装、继承、多态),指同一个方法在不同类中有不同的实现方式。PHP 通过继承和接口实现多态。
通过继承实现多态
子类可以重写父类的方法,调用时根据对象类型执行对应的方法。
class Animal {
public function makeSound() {
echo "Animal sound";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Bark";
}
}
class Cat extends Animal {
public function makeSound() {
echo "Meow";
}
}
$animals = [new Dog(), new Cat()];
foreach ($animals as $animal) {
$animal->makeSound(); // 输出 Bark 和 Meow
}
通过接口实现多态
接口定义方法规范,不同类实现接口并提供具体逻辑。
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return 3.14 * $this->radius * $this->radius;
}
}
class Square implements Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function calculateArea() {
return $this->side * $this->side;
}
}
$shapes = [new Circle(5), new Square(4)];
foreach ($shapes as $shape) {
echo $shape->calculateArea(); // 输出圆的面积和正方形的面积
}
抽象类实现多态
抽象类结合了接口和继承的特性,可以定义抽象方法和具体方法。
abstract class Vehicle {
abstract public function drive();
public function startEngine() {
echo "Engine started";
}
}
class Car extends Vehicle {
public function drive() {
echo "Driving a car";
}
}
class Bike extends Vehicle {
public function drive() {
echo "Riding a bike";
}
}
$vehicles = [new Car(), new Bike()];
foreach ($vehicles as $vehicle) {
$vehicle->drive(); // 输出 Driving a car 和 Riding a bike
}
多态的应用场景
- 插件系统:通过接口统一扩展功能。
- 支付网关:不同支付方式实现同一接口。
- 数据存储:支持多种数据库驱动。
多态的核心是通过统一的调用方式实现不同的行为,提高代码的灵活性和可扩展性。







