Home > Backend Development > PHP Tutorial > __sleep and __wakeup in php

__sleep and __wakeup in php

巴扎黑
Release: 2016-11-23 11:55:02
Original
1331 people have browsed it

In php, __sleep and ___wakeup are two methods that are called before and after object serialization.
Among them, __sleep is called before an object is serialized. It does not receive any parameters, but will return an array. Here you can Place which attributes need to be serialized, such as the following example:

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”;}
Copy after login

Before serialization above, __sleep specified that only the name attribute will be serialized, but creaditcard will not.

On the contrary, __wakeup is triggered before deserialization, such as the following example:

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³
 }
Copy after login

In the above code, because __sleep is used during serialization, the creadit cardnumber attribute is not serialized, so it is Before calling unserialize, the __wakeup method will be called first. For example, here you can re-obtain the data in the database and then perform the operation


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template