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";
}
}
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(3);
$square = new Square(4);
printArea($circle); // 输出: 28.274...
printArea($square); // 输出: 16
通过抽象类实现多态
抽象类定义部分实现,子类完成具体行为:
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";
}
}
function testDrive(Vehicle $vehicle) {
$vehicle->drive();
}
$car = new Car();
$bike = new Bike();
testDrive($car); // 输出: Driving a car
testDrive($bike); // 输出: Riding a bike
类型提示与多态
PHP 的类型提示(Type Hinting)允许在参数中指定接口或父类,实际传入的子类对象会自动匹配:
function processPayment(PaymentGateway $gateway) {
$gateway->process();
}
此方法兼容所有实现 PaymentGateway 接口的类。
动态特性实现多态
PHP 的动态特性允许运行时决定调用方法:
class DynamicExample {
public function handle($type) {
$method = 'handle' . ucfirst($type);
if (method_exists($this, $method)) {
$this->$method();
}
}
private function handleA() {
echo "Handling type A";
}
private function handleB() {
echo "Handling type B";
}
}
$obj = new DynamicExample();
$obj->handle('A'); // 输出: Handling type A
$obj->handle('B'); // 输出: Handling type B
注意事项
- PHP 8.0 引入的联合类型和
match表达式可增强多态处理能力 - 避免过度使用动态方法调用,可能降低代码可读性
- 接口更适合定义严格契约,抽象类适合共享部分实现







