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";
}
}
function animalSound(Animal $animal) {
$animal->makeSound();
}
$dog = new Dog();
$cat = new Cat();
animalSound($dog); // 输出: Bark
animalSound($cat); // 输出: Meow
通过接口实现多态
定义接口并让不同类实现相同接口:
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}
class Square implements Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function calculateArea() {
return pow($this->side, 2);
}
}
function printArea(Shape $shape) {
echo $shape->calculateArea();
}
$circle = new Circle(5);
$square = new Square(4);
printArea($circle); // 输出圆的面积
printArea($square); // 输出正方形的面积
抽象类实现多态
抽象类定义部分实现,强制子类实现特定方法:

abstract class Vehicle {
abstract public function startEngine();
}
class Car extends Vehicle {
public function startEngine() {
echo "Car engine started";
}
}
class Motorcycle extends Vehicle {
public function startEngine() {
echo "Motorcycle engine started";
}
}
function startVehicle(Vehicle $vehicle) {
$vehicle->startEngine();
}
$car = new Car();
$bike = new Motorcycle();
startVehicle($car); // 输出: Car engine started
startVehicle($bike); // 输出: Motorcycle engine started
类型提示与多态
PHP的类型提示确保参数符合特定类/接口,这是实现多态的关键:
function processPayment(PaymentGateway $gateway) {
$gateway->process();
}
动态方法调用
PHP的__call魔术方法可以实现动态多态行为:
class DynamicHandler {
public function __call($name, $arguments) {
if ($name === 'process') {
echo "Processing with " . get_class($arguments[0]);
}
}
}






