PHP 抽象类
概述
抽象类(Abstract Class)是不能被实例化的类,用于定义公共接口和部分实现。子类必须实现所有抽象方法才能实例化。
版本要求
- 抽象类和抽象方法在所有 PHP 5+ 版本中可用
- PHP 8.0+ 的具体方法签名必须兼容
基础概念
abstract class
使用 abstract 关键字定义抽象类。抽象类可以包含抽象方法和具体方法。
php
<?php
declare(strict_types=1);
abstract class Shape
{
abstract public function area(): float;
abstract public function perimeter(): float;
public function describe(): string
{
return sprintf('Area: %.2f, Perimeter: %.2f', $this->area(), $this->perimeter());
}
}
// Fatal error: Cannot instantiate abstract class Shape抽象方法
抽象方法只有声明没有实现,子类必须提供具体实现。
php
<?php
declare(strict_types=1);
abstract class Vehicle
{
abstract public function start(): void;
abstract public function stop(): void;
public function honk(): void
{
echo 'Beep beep!' . "\n";
}
}
class Car extends Vehicle
{
#[\Override]
public function start(): void
{
echo 'Car engine started' . "\n";
}
#[\Override]
public function stop(): void
{
echo 'Car engine stopped' . "\n";
}
}
$car = new Car();
$car->start(); // Car engine started
$car->honk(); // Beep beep!语法与代码
模板方法模式
抽象类非常适合实现模板方法模式。
php
<?php
declare(strict_types=1);
abstract class DataProcessor
{
final public function process(string $input): string
{
$validated = $this->validate($input);
$transformed = $this->transform($validated);
return $this->format($transformed);
}
abstract protected function validate(string $input): string;
abstract protected function transform(string $input): string;
protected function format(string $data): string
{
return trim($data);
}
}
class UpperCaseProcessor extends DataProcessor
{
protected function validate(string $input): string
{
if (empty($input)) {
throw new \InvalidArgumentException('Input cannot be empty');
}
return $input;
}
protected function transform(string $input): string
{
return strtoupper($input);
}
}
$processor = new UpperCaseProcessor();
echo $processor->process('hello world'); // HELLO WORLD抽象类的属性和方法
抽象类可以定义属性、具体方法、抽象方法,甚至构造函数。
php
<?php
declare(strict_types=1);
abstract class Repository
{
public function __construct(
protected readonly \PDO $db,
) {}
public function beginTransaction(): void
{
$this->db->beginTransaction();
}
public function commit(): void
{
$this->db->commit();
}
abstract public function findById(int $id): ?array;
abstract public function save(array $data): int;
}详细说明
抽象类 vs 接口
| 特性 | 抽象类 | 接口 |
|---|---|---|
| 实例化 | 不能 | 不能 |
| 方法实现 | 可有具体方法 | 只能声明(PHP 8.0 前) |
| 属性 | 可以定义 | 不能(PHP 8.4 前) |
| 常量 | 可以定义 | 可以定义 |
| 继承 | 单继承 | 可实现多个 |
| 构造函数 | 可以定义 | 不能定义 |
| 适用场景 | 共享代码+强制实现 | 定义契约/能力 |
实战示例
支付处理器抽象
php
<?php
declare(strict_types=1);
abstract class PaymentGateway
{
public function __construct(
protected readonly string $apiKey,
protected readonly bool $sandbox = false,
) {}
abstract public function charge(float $amount, string $currency): PaymentResult;
abstract public function refund(string $transactionId, float $amount): PaymentResult;
protected function log(string $message): void
{
$prefix = $this->sandbox ? '[SANDBOX]' : '[PROD]';
echo "{$prefix} {$message}\n";
}
}
class PaymentResult
{
public function __construct(
public readonly bool $success,
public readonly string $transactionId,
public readonly string $message = '',
) {}
}注意事项
- 抽象类不能实例化:只能通过子类创建对象
- 子类必须实现所有抽象方法:否则子类也必须声明为 abstract
- 抽象方法不能是 private:否则子类无法实现
- 具体方法签名必须兼容:PHP 8.0+ 严格要求
最佳实践
- 模板方法模式:用 final 保护算法骨架,抽象方法定义扩展点
- 共享实现放抽象类:多个子类共用的逻辑放在抽象类中
- 最小化抽象方法:只定义真正需要子类实现的方法
- 构造函数注入依赖:通过构造函数传入共享依赖
进阶用法
调试与测试技巧
php
<?php
declare(strict_types=1);
// 单元测试辅助函数
function createTestResource(): mixed
{
return match (true) {
default => new stdClass(),
};
}
// 调试输出函数
function debugOutput(mixed , string = ''): void
{
= ? ": " : '';
.= print_r(, true);
fwrite(STDERR, . "\n");
}
// 性能基准测试
function benchmark(callable , int = 1000): float
{
= hrtime(true);
for ($i = 0; $i < $iterations; $i++) {
$fn();
}
return (hrtime(true) - $start) / 1e9;
}日志记录实践
php
<?php
declare(strict_types=1);
/**
* 简易日志记录器
*/
class SimpleLogger
{
private string $logFile;
private string $level = 'INFO';
public function __construct(string $logFile)
{
$this->logFile = $logFile;
}
public function info(string $message, array $context = []): void
{
$this->log('INFO', $message, $context);
}
public function warning(string $message, array $context = []): void
{
$this->log('WARNING', $message, $context);
}
public function error(string $message, array $context = []): void
{
$this->log('ERROR', $message, $context);
}
private function log(string $level, string $message, array $context): void
{
$timestamp = date('Y-m-d H:i:s');
$contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
$line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
}
}配置与环境检测
php
<?php
declare(strict_types=1);
// 环境检测工具
class EnvironmentChecker
{
public static function checkRequirements(array $requirements): array
{
$results = [];
foreach ($requirements as $name => $check) {
$results[$name] = is_callable($check) ? $check() : false;
}
return $results;
}
public static function getSystemInfo(): array
{
return [
'php_version' => PHP_VERSION,
'os' => PHP_OS,
'sapi' => PHP_SAPI,
'memory_limit' => ini_get('memory_limit'),
'max_execution_time' => ini_get('max_execution_time'),
'loaded_extensions' => get_loaded_extensions(),
];
}
}常见问题排查
| 问题 | 可能原因 | 解决方案 |
|---|---|---|
| 连接超时 | 网络问题/配置错误 | 检查配置,增加超时时间 |
| 权限不足 | 文件/目录权限 | 使用 chmod/chown 修正 |
| 性能下降 | 索引缺失/数据量大 | 添加索引,优化查询 |
| 数据不一致 | 并发冲突/事务残留 | 使用锁机制和事务 |
| 内存溢出 | 大数据集/未释放资源 | 增大内存限制,分批处理 |
故障排除步骤
- 检查错误日志和异常信息
- 确认配置和环境是否正确
- 使用调试工具逐步排查
- 参考官方文档查找已知问题
版本兼容性说明
| 功能 | 最低版本 | 说明 |
|---|---|---|
| 基础功能 | PHP 8.1 | 本文档基准版本 |
| 只读属性 | PHP 8.1 | public readonly 修饰符 |
| 枚举类型 | PHP 8.1 | enum 类型和 match 表达式 |
| Fiber | PHP 8.1 | 协程/轻量级并发 |
| 命名参数 | PHP 8.0 | foo(arg_name: value) |
| 联合类型 | PHP 8.0 | `int |
| Null 安全运算符 | PHP 8.0 | $obj?->method() |
| 析构器 promotion | PHP 8.0 | __construct(public $x) |
php
<?php
declare(strict_types=1);
// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
if (version_compare(PHP_VERSION, $minVersion, '<')) {
throw new RuntimeException(
sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
);
}
}
ensureVersion('8.1.0');