In php, _ sleep and _ wakeup & nbsp; in php, __sleep and ___ wakeup are two methods called respectively before and after object serialization, _ sleep is called before an object is serialized. it does not receive any parameters but returns an array. which attributes need to be serialized can be placed here, for example: _ sleep and _ wakeup in classC php
In php, __sleep and ___ wakeup are two methods called respectively before and after object serialization,
_ Sleep is called before an object is serialized. it does not receive any parameters but returns an array. which attributes need to be serialized can be placed here, for 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 "); // only name will be serialized} $ 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 attribute will be serialized, but the creaditcard will not.
On the contrary, _ wakeup is triggered before deserialization. for 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 ") {// Re-obtain $ this-> credit_card_number = "1234567890123456" ;}}$ c = new Customer (); $ c-> setName ("Stuart") in the database "); $ 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) '2017? }
In the above code, because _ sleep is used during serialization and the creadit cardnumber attribute is not serialized, The _ wakeup method is called before unserialize is deserialized, for example, you can retrieve data from the database again.