php魔术方法,__sleep,__wakeup使用
<?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 '</br>'; //序列化时并不会存储 $info 属性 $temp = serialize($boy); echo $temp . PHP_EOL; echo '</br>'; //反序列化时会调用 __wakeup() 函数 $boy = unserialize($temp); //__wakeup() 组装的 $info $boy->getInfo();
posted on 2018-05-31 14:31 running-fly 阅读(509) 评论(0) 编辑 收藏 举报