php多态实现uml
PHP多态实现与UML表示
多态是面向对象编程的核心概念之一,允许不同类的对象对同一消息做出响应。PHP通过继承和接口实现多态,UML类图可清晰描述这种关系。
通过继承实现多态
基类定义通用方法,子类重写该方法实现不同行为:
class Animal {
public function makeSound() {
return "Generic animal sound";
}
}
class Dog extends Animal {
public function makeSound() {
return "Bark";
}
}
class Cat extends Animal {
public function makeSound() {
return "Meow";
}
}
function animalSound(Animal $animal) {
echo $animal->makeSound();
}
$dog = new Dog();
$cat = new Cat();
animalSound($dog); // 输出: Bark
animalSound($cat); // 输出: Meow
UML表示:

- 基类
Animal与子类Dog、Cat之间用带空心三角箭头的实线连接(泛化关系) - 所有类包含
makeSound()方法,子类方法前标注{redefined}
通过接口实现多态
接口定义契约,不同类实现相同接口但行为不同:
interface Payment {
public function pay($amount);
}
class CreditCardPayment implements Payment {
public function pay($amount) {
echo "Paying $amount via Credit Card";
}
}
class PayPalPayment implements Payment {
public function pay($amount) {
echo "Paying $amount via PayPal";
}
}
function processPayment(Payment $payment, $amount) {
$payment->pay($amount);
}
$creditCard = new CreditCardPayment();
$paypal = new PayPalPayment();
processPayment($creditCard, 100);
processPayment($paypal, 200);
UML表示:

- 接口
Payment与实现类之间用带空心三角箭头的虚线连接(实现关系) - 接口名称上方标注
<<interface>>构造型 - 所有实现类必须包含接口定义的
pay()方法
抽象类实现多态
抽象类结合继承和接口特点:
abstract class Shape {
abstract public function calculateArea();
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}
class Square extends Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function calculateArea() {
return pow($this->side, 2);
}
}
function printArea(Shape $shape) {
echo "Area: " . $shape->calculateArea();
}
$circle = new Circle(5);
$square = new Square(4);
printArea($circle);
printArea($square);
UML表示:
- 抽象类
Shape名称用斜体表示 - 抽象方法
calculateArea()同样用斜体标注 - 子类与抽象类之间用泛化关系连接
UML多态关系要点
- 泛化关系(继承):空心三角箭头+实线,表示"is-a"关系
- 实现关系(接口):空心三角箭头+虚线,表示契约实现
- 抽象元素:类名和方法名使用斜体表示
- 方法覆盖:子类重写方法可添加
{redefined}标注 - 多态调用:在UML序列图中可展示运行时对象类型与动态绑定
多态实现的关键在于统一接口不同实现,UML通过清晰的类关系和标注展示这种灵活性。实际建模时应根据具体场景选择继承或接口方式。






