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();
}
通过接口实现多态
接口定义方法签名,不同类实现接口并提供具体实现。
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 move();
public function startEngine() {
echo "Engine started";
}
}
class Car extends Vehicle {
public function move() {
echo "Car is moving";
}
}
class Bike extends Vehicle {
public function move() {
echo "Bike is moving";
}
}
$vehicles = [new Car(), new Bike()];
foreach ($vehicles as $vehicle) {
$vehicle->move();
}
类型提示与多态
在函数参数中使用类型提示,可以接受实现特定接口或继承特定类的对象。
function makeSound(Animal $animal) {
$animal->makeSound();
}
makeSound(new Dog());
makeSound(new Cat());
魔术方法实现多态
通过魔术方法如__call实现动态方法调用,增加灵活性。
class Polymorphic {
public function __call($name, $arguments) {
if ($name == 'execute') {
echo "Executing with arguments: " . implode(', ', $arguments);
}
}
}
$poly = new Polymorphic();
$poly->execute('arg1', 'arg2');
多态的应用场景
多态常用于需要处理多种类型对象的场景,如支付系统、日志系统等。通过多态可以降低代码耦合度,提高扩展性。






