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 Dog(), new Cat()];
foreach ($animals as $animal) {
$animal->makeSound();
}
通过接口实现多态
接口定义了一组方法,任何实现接口的类必须实现这些方法,从而实现多态。
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(5), new Square(4)];
foreach ($shapes as $shape) {
echo $shape->area() . "\n";
}
通过抽象类实现多态
抽象类可以包含抽象方法和具体方法,子类必须实现抽象方法,从而实现多态。
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();
}
使用类型提示实现多态
PHP 的类型提示可以确保传入的对象实现特定接口或继承特定类,从而保证多态的正确性。
function printArea(Shape $shape) {
echo $shape->area() . "\n";
}
printArea(new Circle(5));
printArea(new Square(4));
动态方法调用实现多态
PHP 允许动态调用方法,可以通过变量存储方法名并调用。

class Printer {
public function printText($text) {
echo $text;
}
}
$printer = new Printer();
$method = 'printText';
$printer->$method("Hello, World!");
通过以上方法,PHP 可以实现灵活的多态性,使代码更具扩展性和可维护性。






