序列化(serialize)和反序列化(unserialize)以及__sleep()函式和__wakeup()函式
序列化資料就是將資料轉化成一個基於文字的格式,以便儲存。
__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’
}