PHP 魔术方法:__serialize / __unserialize
概述
__serialize 和 __unserialize 是 PHP 7.4+ 引入的序列化魔术方法,作为 __sleep / __wakeup 的推荐替代方案。它们提供更灵活和安全的序列化控制。
版本要求
- PHP 7.4+:__serialize / __unserialize
基础概念
与 __sleep / __wakeup 的区别
| 特性 | __sleep / __wakeup | __serialize / __unserialize |
|---|---|---|
| PHP 版本 | 所有 PHP 5+ | PHP 7.4+ |
| 控制方式 | 返回属性名数组 | 返回自定义数据数组 |
| 数据格式 | 属性名列表 | 任意键值对 |
| 灵活性 | 低 | 高 |
| 安全性 | 较低(可能遗漏属性) | 较高(显式控制数据) |
| 与 Serializable 接口 | 不相关 | 优先级低于 Serializable |
语法与代码
基本用法
php
<?php
declare(strict_types=1);
class User
{
public function __construct(
public readonly int $id,
public readonly string $name,
private readonly string $token,
) {}
public function __serialize(): array
{
return [
'id' => $this->id,
'name' => $this->name,
// token 不包含在序列化数据中
];
}
public function __unserialize(array $data): void
{
$this->id = $data['id'];
$this->name = $data['name'];
$this->token = bin2hex(random_bytes(16));
}
}
$user = new User(1, 'Alice', 'secret-token');
$serialized = serialize($user);
$restored = unserialize($serialized);
echo $restored->id; // 1
echo $restored->name; // Alice
echo $restored->token !== 'secret-token' ? 'new token' : 'old token'; // new token数据转换
__serialize 可以返回与属性名不同的键,实现数据格式转换。
php
<?php
declare(strict_types=1);
class Product
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly int $priceInCents,
) {}
public function __serialize(): array
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->priceInCents / 100, // 转为元
];
}
public function __unserialize(array $data): void
{
$this->id = $data['id'];
$this->name = $data['name'];
$this->priceInCents = (int) ($data['price'] * 100); // 转回分
}
}
$product = new Product(1, 'Laptop', 99999);
$serialized = serialize($product);
$restored = unserialize($serialized);
echo $restored->priceInCents; // 99999详细说明
与 Serializable 接口的关系
如果类同时实现了 Serializable 接口和 __serialize/__unserialize,优先使用 Serializable 接口。
php
<?php
declare(strict_types=1);
class LegacyClass implements \Serializable
{
public function serialize(): string
{
return json_encode(['legacy' => true]);
}
public function unserialize(string $data): void
{
$decoded = json_decode($data, true);
}
// 这些方法不会被调用(Serializable 优先)
public function __serialize(): array
{
return [];
}
public function __unserialize(array $data): void
{
}
}优先级规则
- 类实现了
Serializable-> 使用 Serializable - 类定义了
__serialize/__unserialize-> 使用魔术方法 - 都没有 -> 使用默认行为(序列化所有属性)
嵌套对象的序列化
php
<?php
declare(strict_types=1);
class Address
{
public function __construct(
public readonly string $city,
public readonly string $street,
) {}
}
class Company
{
public function __construct(
public readonly string $name,
public readonly Address $address,
public readonly array $employees = [],
) {}
public function __serialize(): array
{
return [
'name' => $this->name,
'address' => $this->address, // Address 对象自动序列化
'employeeCount' => count($this->employees),
];
}
public function __unserialize(array $data): void
{
$this->name = $data['name'];
$this->address = $data['address'];
}
}
$company = new Company(
'Tech Corp',
new Address('Beijing', 'ChangAn'),
['Alice', 'Bob'],
);
$serialized = serialize($company);
$restored = unserialize($serialized);
echo $restored->address->city; // Beijing实战示例
完整序列化示例
php
<?php
declare(strict_types=1);
class ApiConnection
{
private string $apiKey;
private string $baseUrl;
private int $requestCount = 0;
private ?\PDO $cache = null;
public function __construct(string $apiKey, string $baseUrl)
{
$this->apiKey = $apiKey;
$this->baseUrl = $baseUrl;
}
public function __serialize(): array
{
return [
'apiKey' => $this->apiKey,
'baseUrl' => $this->baseUrl,
'requestCount' => $this->requestCount,
// PDO 连接不序列化
];
}
public function __unserialize(array $data): void
{
$this->apiKey = $data['apiKey'];
$this->baseUrl = $data['baseUrl'];
$this->requestCount = $data['requestCount'];
// 重新初始化缓存
$this->cache = null;
}
public function getRequestCount(): int
{
return $this->requestCount;
}
}
$connection = new ApiConnection('key-123', 'https://api.example.com');
$serialized = serialize($connection);
$restored = unserialize($serialized);
echo $restored->getRequestCount(); // 0注意事项
- PHP 7.4+ 才可用:旧版本 PHP 不支持
- 与 __sleep 互斥:如果定义了 __serialize,__sleep 不会被调用
- Serializable 接口优先:同时实现时使用接口
- 数据完整性:确保 __unserialize 能正确还原所有必要数据
最佳实践
- PHP 7.4+ 优先使用 __serialize:比 __sleep 更安全灵活
- 排除敏感数据:不在序列化数据中包含密钥、token
- 排除不可序列化资源:如数据库连接、文件句柄
- 保持版本兼容:添加版本号字段处理数据格式变更
- 考虑使用 JSON:对于跨语言场景,JSON 更通用
进阶用法
调试与测试技巧
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');