PHP 协变与逆变
概述
协变(Covariance)和逆变(Contravariance)是类型系统中关于子类型关系在复合类型中传播方向的概念。PHP 7.4+ 支持参数逆变,PHP 8.0+ 支持返回值协变。
版本要求
- PHP 7.4+:返回值类型协变(部分支持)、参数类型逆变
- PHP 8.0+:完整的返回值类型协变
基础概念
里氏替换原则(LSP)
子类对象必须能替换父类对象而不破坏程序行为。协变和逆变是 LSP 在类型系统中的具体表现。
协变
返回值类型可以更具体(子类型方向相同)。父类返回 Animal,子类可以返回 Dog。
逆变
参数类型可以更宽泛(子类型方向相反)。父类接受 Dog,子类可以接受 Animal。
语法与代码
返回值协变
php
<?php
declare(strict_types=1);
class Animal
{
public function getOwner(): ?Person
{
return null;
}
}
class Dog extends Animal
{
// 协变:返回更具体的 DogOwner
public function getOwner(): ?DogOwner
{
return null;
}
}
class Person {}
class DogOwner extends Person {}参数逆变
php
<?php
declare(strict_types=1);
class FoodProcessor
{
public function process(AnimalFood $food): void
{
echo "Processing animal food\n";
}
}
class UniversalProcessor extends FoodProcessor
{
// 逆变:接受更宽泛的 Food 类型
public function process(Food $food): void
{
echo "Processing any food\n";
}
}
interface AnimalFood {}
interface Food {}
class Meat implements AnimalFood, Food {}接口中的协变
php
<?php
declare(strict_types=1);
interface Repository
{
public function find(int $id): ?Entity;
}
class UserRepository implements Repository
{
// 协变:返回更具体的 User
public function find(int $id): ?User
{
return null;
}
}
class Entity {}
class User extends Entity {}详细说明
PHP 7.4 vs PHP 8.0 的差异
| 特性 | PHP 7.4 | PHP 8.0 |
|---|---|---|
| 返回值协变 | 仅类返回类型 | 类+联合类型 |
| 参数逆变 | 支持 | 支持 |
| static 返回类型 | - | 支持 |
| self 返回类型协变 | - | 支持 |
实战示例
工厂接口的协变
php
<?php
declare(strict_types=1);
interface Factory
{
public function create(): Entity;
}
class UserFactory implements Factory
{
// 协变:返回更具体的 User
public function create(): User
{
return new User();
}
}
class Entity {}
class User extends Entity {}注意事项
- PHP 7.4 前不支持:PHP 7.4 之前的方法重写签名必须完全一致
- private 方法不受约束:private 方法不需要遵循协变逆变规则
- 构造函数不受约束:子类构造函数签名可以完全不同
- 接口中的默认实现也需要兼容
最佳实践
- 利用协变返回具体类型:让子类返回更精确的类型
- 利用逆变放宽参数:让子类接受更通用的输入
- 遵循 LSP 原则:确保子类可以安全替换父类
- 类型声明越具体越好:提高代码的类型安全性
进阶用法
调试与测试技巧
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');