欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php中__sleep和__wakeup

程序员文章站 2022-03-20 20:45:00
...
在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方法,比如这里可以重新在数据库中取得数据,再此进行操作