php实现多态
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 Animal(), new Dog(), new Cat()];
foreach ($animals as $animal) {
$animal->makeSound();
}
通过接口实现多态
接口定义一组方法签名,不同类实现相同接口但提供不同实现。
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $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();
}
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();
}
类型提示与多态
方法参数使用父类或接口类型提示,可以接受任何子类或实现类的实例。
function makeSound(Animal $animal) {
$animal->makeSound();
}
makeSound(new Dog());
makeSound(new Cat());
动态方法调用
PHP 支持动态调用方法,进一步增强多态性。
class Printer {
public function printDocument() {
echo "Printing document";
}
}
class Fax {
public function sendFax() {
echo "Sending fax";
}
}
function execute($device, $method) {
$device->$method();
}
execute(new Printer(), 'printDocument');
execute(new Fax(), 'sendFax');
多态的优势
- 提高代码可扩展性,新增类不影响现有代码
- 减少条件语句,通过对象类型自动决定行为
- 增强代码复用,公共行为可放在父类或接口中
通过合理使用继承、接口和抽象类,可以在 PHP 中有效实现多态,构建灵活可扩展的面向对象系统。






