PHP 魔术方法:__sleep / __wakeup
概述
__sleep 和 __wakeup 是 PHP 序列化相关的魔术方法。__sleep 在 serialize() 时调用,用于指定哪些属性需要序列化。__wakeup 在 unserialize() 时调用,用于重新初始化对象。
版本要求
- __sleep / __wakeup 在所有 PHP 5+ 版本中可用
- PHP 7.4+:推荐使用 __serialize / __unserialize 替代方案
基础概念
__sleep
__sleep 返回一个数组,包含需要被序列化的属性名。用于清理不需要持久化的数据(如数据库连接)。
__wakeup
__wakeup 在反序列化后自动调用,用于重新建立数据库连接或重新初始化资源。
语法与代码
基本用法
php
<?php
declare(strict_types=1);
class SessionData
{
public string $userId;
public string $userName;
private \PDO $db; // 不可序列化
public function __construct(string $userId, string $userName)
{
$this->userId = $userId;
$this->userName = $userName;
$this->db = new \PDO('sqlite::memory:');
}
public function __sleep(): array
{
// 只序列化需要的属性
return ['userId', 'userName'];
}
public function __wakeup(): void
{
// 重新建立数据库连接
$this->db = new \PDO('sqlite::memory:');
echo "Reconnected DB for user: {$this->userId}\n";
}
}
$session = new SessionData('123', 'Alice');
$serialized = serialize($session);
echo $serialized;
$restored = unserialize($serialized);
echo $restored->userId; // 123
echo $restored->userName; // Alice__sleep 的清理作用
php
<?php
declare(strict_types=1);
class Logger
{
private $fileHandle;
public array $logs = [];
public function __construct(string $path)
{
$this->fileHandle = fopen($path, 'a');
}
public function __sleep(): array
{
// 关闭文件句柄,不序列化资源
fclose($this->fileHandle);
$this->fileHandle = null;
return ['logs'];
}
public function __wakeup(): void
{
// 重新打开文件
$this->fileHandle = fopen('/tmp/app.log', 'a');
}
}详细说明
__sleep 返回值要求
- 必须返回包含属性名的字符串数组
- 返回的属性必须是实际存在的
- 不返回的属性在序列化后丢失(值类型)或设为 null
与 __serialize / __unserialize 的关系
PHP 7.4+ 推荐使用 __serialize / __unserialize,它们提供了更灵活和安全的序列化控制。
php
<?php
declare(strict_types=1);
// 旧方式:__sleep / __wakeup
class OldWay
{
public string $data;
public function __sleep(): array
{
return ['data'];
}
public function __wakeup(): void
{
// 重新初始化
}
}
// 新方式:__serialize / __unserialize(PHP 7.4+)
class NewWay
{
public function __serialize(): array
{
return ['data' => $this->data];
}
public function __unserialize(array $data): void
{
$this->data = $data['data'];
}
}实战示例
带缓存的配置对象
php
<?php
declare(strict_types=1);
class AppConfig
{
public string $appName;
public string $environment;
private array $cache = [];
private ?\PDO $db = null;
public function __construct(string $appName, string $environment = 'production')
{
$this->appName = $appName;
$this->environment = $environment;
}
public function __sleep(): array
{
return ['appName', 'environment'];
}
public function __wakeup(): void
{
$this->cache = [];
if ($this->environment === 'development') {
$this->db = new \PDO('sqlite::memory:');
}
}
public function get(string $key, mixed $default = null): mixed
{
if (!isset($this->cache[$key])) {
$this->cache[$key] = $default;
}
return $this->cache[$key];
}
}
$config = new AppConfig('MyApp', 'development');
$serialized = serialize($config);
$restored = unserialize($serialized);
echo $restored->appName; // MyApp注意事项
- __sleep 不能抛出异常:可能导致序列化失败
- 资源类型不能序列化:如文件句柄、PDO 连接
- PHP 7.4+ 推荐新 API:__serialize / __unserialize 更安全
- 安全性:不要序列化敏感数据
最佳实践
- PHP 7.4+ 优先使用 __serialize/__unserialize
- __sleep 中清理资源:关闭文件句柄、数据库连接
- __wakeup 中重新初始化:重建依赖关系
- 避免序列化对象:考虑使用 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');