在php中,__sleep和___wakeup是兩個分別自物件序列化前後分別調用的方法,
其中__sleep在一個物件序列化前調用,它不接收任何參數,但會返回數組,這裡可以要放置哪些屬性需要序列化,例如下面的例子:
class Customer { private $name; private $credit_card_number; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } public function setCC($cc) { $this->credit_card_number = $cc; } public function getCC() { return $this->credit_card_number; } public function __sleep() { return array(“name”); //只有name会序列化 } } $c = new Customer(); $c->setName(“Stuard”); $c->setCC(“456789″); $data = serialize($c).”\n”; echo $data.”\n”; Output: O:8:”Customer”:1:{s:14:” Customer name”;s:5:”Stuard”;}
上面在序列化前,__sleep中指定了只有name屬性會序列化,而creaditcard不會。
而__wakeup則相反,它是在反序列化前觸發的,例如下面例子:
class Customer { private $name; private $credit_card_number; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } public function setCC($cc) { $this->credit_card_number = $cc; } public function getCC() { return $this->credit_card_number; } public function __sleep() { return array(“name”); } public function __wakeup() { if($this->name == “Stuart”) { //重新在数据库中获得 $this->credit_card_number = “1234567890123456″; } } } $c = new Customer(); $c->setName(“Stuart”); $c->setCC(“1234567890123456″); $data = serialize($c).”\n”; var_dump(unserialize($data)); Output: object(Customer)#2 (2) { ["name:private"]=> string(5) “Stuart” ["credit_card_number:private"]=> string(16) ’1234567890123456³ }
上面的程式碼中,因為序列化時使用了__sleep,沒把creadit cardnumber屬性序列化,因此在反序列化unserialize呼叫前,會先呼叫__wakeup方法,例如這裡可以重新在資料庫中取得數據,再此進行操作