首頁 >後端開發 >php教程 >php中__sleep和__wakeup

php中__sleep和__wakeup

巴扎黑
巴扎黑原創
2016-11-23 11:55:021308瀏覽

在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方法,例如這裡可以重新在資料庫中取得數據,再此進行操作


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn