PHP 魔术函数之 __sleep()/__wakeup()
__sleep()
触发事件:对象被序列化之前
作用:返回需要被序列化存储的成员属性,删减不必要
返回:array 需要被序列化存储的成员属性数组
__wakeup()
触发事件:类的实例的序列化串被反序列化时
作用:预先准备对象资源
返回:void
实例:
class Person
{
private $name, $age, $sex, $info;
public function __construct( $name, $age, $sex )
{
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
$this->info = sprintf("prepared by construct magic functionname: %s age: %d sex: %s",
$this->name, $this->age, $this->sex);
}
public function getInfo()
{
echo $this->info . PHP_EOL;
}
/**
* serialize前调用 用于删选需要被序列化存储的成员变量
* @return array [description]
*/
public function __sleep()
{
echo __METHOD__ . PHP_EOL;
//序列化时只会存储 name age sex, info 不会被序列化
return ['name', 'age', 'sex'];
}
/**
* unserialize前调用 用于预先准备对象资源
*/
public function __wakeup()
{
echo __METHOD__ . PHP_EOL;
$this->info = sprintf("prepared by wakeup magic function name: %s age: %d sex: %s",
$this->name, $this->age, $this->sex);
}
}
$boy = new Person( 'sallency', 25, 'male' );
//构造函数组装的 $info
$boy->getInfo();
//序列化时并不会存储 $info 属性
$temp = serialize($boy);
echo $temp . PHP_EOL;
//反序列化时会调用 __wakeup() 函数
$boy = unserialize($temp);
//__wakeup() 组装的 $info
$boy->getInfo();
?>