PHP in __sleep and __wakeup
In PHP, __sleep and ___wakeup are two separate methods that are called before and after the object is serialized,
Where __sleep is called before an object is serialized, it does not receive any arguments, but returns an array where the properties that need to be serialized can be placed, 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 Fun Ction SETCC ($cc) {$this->credit_card_number = $cc;} public Function GETCC () {return $this->credit_card_number;} Public Function __sleep () {return Array ("name");//Only name will serialize}} $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";}
Before serialization, __sleep specifies that only the Name property is serialized, and Creaditcard does not.
__wakeup, on the other hand, 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 Fun Ction 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") { //heavy New in the database $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? }
In the above code, because __sleep is used in serialization, the Creadit Cardnumber property is not serialized, so the __wakeup method is called before deserializing the unserialize call, such as the ability to re-obtain the data in the database before doing so