魔术方法__sleep 和 __wakeup
感觉序列化和反序列化用得倒是比较少了,而json_encode和json_decode用得相对多,都是转化成串,进行入库、传输等。json更方便,但是序列化和反序列化结合这两个魔术方法使用倒还行
<?php /** * 魔术方法__sleep() 和 __wakeup() * __sleep(): serialize()序列化之前调用,返回一个需要保存变量名数组。一般用来保存部分属性,节省空间 * __wakeup():unserialize() 反序列化之前调用,无返回值,一般进行一个动作 */ class Test{ public $s = 'hehe'; public $a = 'world'; public function __sleep(){ return array('a');//序列化只保存a } public function __wakeup(){ $this->a = 'hello';//反序列化时进行a值的修改动作 } } $m = new Test(); $n = serialize($m); $m = unserialize($m); var_dump($m); ?>
下面看 __sleep __wakeup 在手册给出的一个例子
<?php class Connection { protected $link; private $server, $username, $password, $db; public function __construct($server, $username, $password, $db) { $this->server = $server; $this->username = $username; $this->password = $password; $this->db = $db; $this->connect(); } private function connect() { $this->link = mysql_connect($this->server, $this->username, $this->password); mysql_select_db($this->db, $this->link); } public function __sleep() { return array('server', 'username', 'password', 'db'); } public function __wakeup() { $this->connect(); } } ?>