<?php
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();
echo "<hr>";
//序列化时并不会存储 $info 属性
$temp = serialize($boy);
echo $temp . PHP_EOL;
echo "<hr>";
//反序列化时会调用 __wakeup() 函数
$boy = unserialize($temp);
//__wakeup() 组装的 $info
$boy->getInfo();
echo "<hr>";
转自 https://my.oschina.net/sallency/blog/629206