php用那几种形式实现多态
多态的基本概念
多态是面向对象编程的核心特性之一,允许不同类的对象对同一消息作出不同响应。在PHP中,多态主要通过以下几种形式实现。
方法重写(Override)
子类继承父类后,可以重写父类的方法,实现不同的行为。调用时根据对象类型决定执行哪个方法。

class Animal {
public function makeSound() {
echo "Animal sound";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Bark";
}
}
$animal = new Dog();
$animal->makeSound(); // 输出 "Bark"
接口(Interface)实现
通过接口定义方法规范,不同类实现同一接口但逻辑不同,实现多态。

interface Shape {
public function area();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return pi() * $this->radius * $this->radius;
}
}
class Square implements Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function area() {
return $this->side * $this->side;
}
}
$shapes = [new Circle(3), new Square(4)];
foreach ($shapes as $shape) {
echo $shape->area() . "\n";
}
抽象类(Abstract Class)
抽象类定义部分实现,子类继承后完成具体逻辑。通过抽象方法强制子类实现多态行为。
abstract class Vehicle {
abstract public function drive();
}
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();
}
类型提示与多态
通过类型提示(Type Hinting)约束参数类型为接口或父类,实际传入不同子类对象实现多态。
function printArea(Shape $shape) {
echo $shape->area();
}
printArea(new Circle(2)); // 输出圆的面积
printArea(new Square(3)); // 输出正方形的面积
总结
PHP中实现多态的主要方式包括方法重写、接口实现、抽象类继承以及类型提示。这些方法均基于对象的具体类型动态调用相应逻辑,符合面向对象的设计原则。

