php多态实现
PHP 多态的实现方式
多态是面向对象编程的核心概念之一,允许不同类的对象对同一消息作出响应。PHP 中主要通过以下几种方式实现多态。
通过接口实现多态
定义接口并让不同类实现该接口,确保这些类具有相同的方法签名。
interface Animal {
public function makeSound();
}
class Dog implements Animal {
public function makeSound() {
echo "Bark";
}
}
class Cat implements Animal {
public function makeSound() {
echo "Meow";
}
}
function animalSound(Animal $animal) {
$animal->makeSound();
}
$dog = new Dog();
$cat = new Cat();
animalSound($dog); // 输出: Bark
animalSound($cat); // 输出: Meow
通过抽象类实现多态
抽象类可以定义部分实现,子类继承并实现抽象方法。
abstract class Shape {
abstract public function area();
}
class Rectangle extends Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function area() {
return $this->width * $this->height;
}
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return pi() * $this->radius * $this->radius;
}
}
function printArea(Shape $shape) {
echo $shape->area();
}
$rectangle = new Rectangle(5, 10);
$circle = new Circle(7);
printArea($rectangle); // 输出: 50
printArea($circle); // 输出: ~153.938
通过方法重写实现多态
子类可以重写父类的方法,实现不同的行为。
class Vehicle {
public function drive() {
echo "Driving a vehicle";
}
}
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
通过魔术方法实现多态
PHP 的魔术方法如 __call 和 __callStatic 可以实现动态方法调用。
class DynamicPolymorphism {
public function __call($name, $arguments) {
if ($name === 'process') {
if (count($arguments) === 1) {
echo "Processing single argument: " . $arguments[0];
} elseif (count($arguments) === 2) {
echo "Processing two arguments: " . $arguments[0] . ", " . $arguments[1];
}
}
}
}
$obj = new DynamicPolymorphism();
$obj->process("hello"); // 输出: Processing single argument: hello
$obj->process("hello", "world"); // 输出: Processing two arguments: hello, world
通过 Traits 实现多态
Traits 可以复用代码,并在不同类中实现多态行为。

trait Loggable {
public function log($message) {
echo "Log: " . $message;
}
}
class User {
use Loggable;
}
class Product {
use Loggable;
}
$user = new User();
$product = new Product();
$user->log("User created"); // 输出: Log: User created
$product->log("Product created"); // 输出: Log: Product created
总结
PHP 中实现多态的主要方式包括接口、抽象类、方法重写、魔术方法和 Traits。选择合适的方式取决于具体需求,接口和抽象类适合定义规范,方法重写和 Traits 适合代码复用,魔术方法适合动态行为。






