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 Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function calculateArea() {
return $this->width * $this->height;
}
}
function printArea(Shape $shape) {
echo $shape->calculateArea();
}
$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);
printArea($circle); // 输出圆的面积
printArea($rectangle); // 输出矩形的面积
类型提示与多态
PHP的类型提示(类型声明)可以指定参数必须是某个类或接口的实例,这是实现多态的关键。函数或方法参数使用父类或接口类型提示,可以接受任何子类或实现类的对象。
抽象类实现多态
抽象类定义部分实现,要求子类完成剩余实现,也是一种多态实现方式。
abstract class Vehicle {
abstract public function drive();
}
class Car extends Vehicle {
public function drive() {
echo "Driving a car";
}
}
class Truck extends Vehicle {
public function drive() {
echo "Driving a truck";
}
}
function testDrive(Vehicle $vehicle) {
$vehicle->drive();
}
$car = new Car();
$truck = new Truck();
testDrive($car); // 输出: Driving a car
testDrive($truck); // 输出: Driving a truck
多态的优势
代码更灵活可扩展,新增类无需修改现有代码。提高代码复用性,减少条件判断。使程序更符合开闭原则(对扩展开放,对修改关闭)。







