PHP 不对称属性可见性
概述
不对称属性可见性(Asymmetric Property Visibility)是 PHP 8.4 引入的特性,允许属性的读取和写入设置不同的访问范围。最常见的用法是 public private(set),即公开可读、私有可写。
版本要求
- PHP 8.4+:不对称属性可见性
- PHP 8.5+:静态属性也支持不对称可见性
基础概念
为什么需要不对称可见性
在传统的封装模式中,属性设为 private,然后通过 public getter 方法提供读取。PHP 8.4 的不对称可见性让这一模式变得更简洁。
php
<?php
declare(strict_types=1);
// 传统方式
class UserOld
{
private string $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
}
// PHP 8.4 不对称可见性
class User
{
public function __construct(
public private(set) string $name,
) {}
}
$user = new User('Alice');
echo $user->name; // Alice(public 读取)
// $user->name = 'Bob'; // Error: private(set)(私有写入)语法与代码
基本语法
可见性(set) 可见性:主可见性控制读取,括号内控制写入。
php
<?php
declare(strict_types=1);
class Book
{
public function __construct(
public private(set) string $title,
public protected(set) string $author,
protected private(set) int $pubYear,
) {}
}
class SpecialBook extends Book
{
public function update(string $author, int $year): void
{
$this->author = $author; // OK: protected(set)
// $this->pubYear = $year; // Fatal: private(set)
}
}
$b = new Book('PHP 8.4 Guide', 'Author', 2024);
echo $b->title; // OK: public 读取
echo $b->author; // OK: public 读取
// echo $b->pubYear; // Fatal: protected 读取省略主可见性
当主可见性为 public 时,public 可以省略。
php
<?php
declare(strict_types=1);
class Config
{
public function __construct(
private(set) string $appName, // 等同于 public private(set)
private(set) int $maxConnections,
) {}
}详细说明
规则与限制
- 只有类型化属性才能有 set 可见性
- set 可见性不能比主可见性更宽:
protected public(set)非法 - private(set) 属性自动变为 final:不能在子类中重新声明
- 声明中不允许空格:
private(set)正确,private( set )错误
与 readonly 的区别
| 特性 | readonly | public private(set) |
|---|---|---|
| PHP 版本 | 8.1+ | 8.4+ |
| 初始化 | 只能初始化一次 | 只能初始化一次(通过构造器) |
| 子类设置 | PHP 8.4 起 protected(set) 可被子类设置 | private(set) 不可被子类设置 |
| 钩子兼容 | 不兼容属性挂钩 | 兼容属性挂钩 |
| 灵活性 | 较低 | 较高 |
继承规则
子类可以扩大主可见性或 set 可见性(只要不比父类更严格)。
php
<?php
declare(strict_types=1);
class Book
{
protected string $title;
public protected(set) string $author;
protected private(set) int $pubYear;
}
class SpecialBook extends Book
{
public protected(set) string $title; // OK: 读取放宽
// public protected(set) int $pubYear; // Error: private(set) 是 final
}实战示例
不可变实体
php
<?php
declare(strict_types=1);
class Order
{
public function __construct(
public private(set) readonly int $id,
public private(set) string $customerName,
public private(set) string $status = 'pending',
public private(set) \DateTimeImmutable $createdAt = new \DateTimeImmutable(),
) {}
public function markAsShipped(): void
{
$this->status = 'shipped';
}
public function cancel(): void
{
if ($this->status === 'shipped') {
throw new \RuntimeException('Cannot cancel shipped order');
}
$this->status = 'cancelled';
}
}
$order = new Order(1, 'Alice');
echo $order->status; // pending
$order->markAsShipped();
echo $order->status; // shipped
// $order->id = 2; // Error: private(set) + readonly注意事项
- private(set) 属性是 final 的:不能在子类中重新声明
- 引用获取遵循 set 可见性:获取引用可能修改值
- 数组写入遵循 set 可见性:涉及内部 get/set 操作
- 与属性挂钩兼容:可以同时使用不对称可见性和属性挂钩
最佳实践
- 新代码优先使用 public private(set) 替代手动 getter
- 构造器属性提升+不对称可见性:简洁且安全
- 需要子类修改时用 protected(set)
- 需要公开修改时用 public public(set) 或直接 public
- 与属性挂钩组合使用:需要验证逻辑时在 set 钩子中实现
进阶用法
调试与测试技巧
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');