当前位置:首页 > PHP

php用那几种形式实现多态

2026-01-29 00:12:19PHP

PHP 实现多态的方式

多态是面向对象编程的重要特性,PHP 主要通过以下几种方式实现多态:

方法重写(Override)

子类继承父类后,可以重写父类的方法,实现不同的行为。调用时根据对象类型决定执行哪个方法。

php用那几种形式实现多态

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() * pow($this->radius, 2);
    }
}

class Square implements Shape {
    private $side;

    public function __construct($side) {
        $this->side = $side;
    }

    public function area() {
        return pow($this->side, 2);
    }
}

$shapes = [new Circle(2), new Square(3)];
foreach ($shapes as $shape) {
    echo $shape->area() . "\n";
}

抽象类(Abstract Class)

抽象类可以定义抽象方法,子类必须实现这些方法。抽象类允许部分实现,而接口完全无实现。

php用那几种形式实现多态

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));

魔术方法(Magic Methods)

利用 __call__callStatic 等魔术方法,可以在运行时动态处理不同的方法调用,实现多态行为。

class DynamicHandler {
    public function __call($name, $arguments) {
        if ($name === 'process') {
            echo "Processing with " . implode(', ', $arguments);
        }
    }
}

$handler = new DynamicHandler();
$handler->process('data1', 'data2');

总结

PHP 实现多态的核心方式包括方法重写、接口、抽象类、类型提示和魔术方法。通过这些机制,可以编写灵活且可扩展的面向对象代码。

标签: 几种形式
分享给朋友:

相关文章

jquery选择器有几种

jquery选择器有几种

jQuery选择器类型 jQuery选择器允许开发者通过多种方式选取DOM元素,主要分为以下几类: 基本选择器 $("#id"):通过元素的id属性选取,如$("#header")。…