抽象类 #
一、抽象类基础 #
1.1 定义抽象类 #
php
<?php
abstract class Animal
{
protected string $name;
public function __construct(string $name)
{
$this->name = $name;
}
abstract public function speak(): string;
public function move(): string
{
return "{$this->name} is moving";
}
}
1.2 继承抽象类 #
php
<?php
class Dog extends Animal
{
public function speak(): string
{
return "{$this->name} says Woof!";
}
}
class Cat extends Animal
{
public function speak(): string
{
return "{$this->name} says Meow!";
}
}
二、模板方法模式 #
php
<?php
abstract class DataExporter
{
final public function export(array $data): string
{
$formatted = $this->format($data);
return $this->output($formatted);
}
abstract protected function format(array $data): string;
protected function output(string $data): string
{
return $data;
}
}
class CsvExporter extends DataExporter
{
protected function format(array $data): string
{
$lines = [];
foreach ($data as $row) {
$lines[] = implode(',', $row);
}
return implode("\n", $lines);
}
}
三、抽象类 vs 接口 #
| 特性 | 抽象类 | 接口 |
|---|---|---|
| 实现 | 单继承 | 多实现 |
| 属性 | 可以有 | 只有常量 |
| 方法 | 可具体可抽象 | 默认抽象 |
| 构造函数 | 可以有 | 无 |
四、总结 #
本章学习了:
- 抽象类定义
- 抽象方法
- 模板方法模式
- 抽象类与接口的区别
下一章将学习Trait。
最后更新:2026-03-26