Home >Backend Development >PHP Tutorial >Section 13--Object Serialization--ClassesandObjectsinPHP513_PHP Tutorial
+------------------------------------------------- ----------------------------------+ | = This article is read by Haohappy> | = Chapter Classes and Objects Notes | = Translation + personal experience | = Please do not reprint to avoid unnecessary trouble, thank you | = Criticisms and corrections are welcome, and I hope to make progress together with all PHP enthusiasts! +--------- -------------------------------------------------- --------------------+ */ Section 13 - Object serialization Serialization can convert variables, including objects, into continuous bytes data. You can Store the serialized variables in a file or transmit them over the network. Then deserialize and restore them to the original data. For classes you define before deserializing the class objects, PHP can successfully store its objects. Properties and methods. Sometimes you may need an object to be executed immediately after deserialization. For such purposes, PHP will automatically look for the __sleep and __wakeup methods. When an object is serialized, PHP will call the __sleep method (if present). After deserializing an object, PHP will call the __wakeup method. Neither method accepts parameters. The __sleep method must return an array containing the properties that need to be serialized. PHP will discard the other The value of the attribute. Without the __sleep method, PHP will save all attributes. Example 6.16 shows how to use the __sleep and __wakeup methods to serialize an object. The Id attribute is a temporary attribute that is not intended to be retained in the object. __sleep method ensures that the id attribute is not included in the serialized object. When deserializing a User object, the __wakeup method establishes a new value for the id attribute. This example is designed to be self-sustaining. In actual development, you may find that the resource contains Objects (such as images or data streams) require these methods. Listing 6.16 Object serialization id = uniqid(); } function __sleep() { //do not serialize this->id Do not serialize id return(array( "name")); } function __wakeup() { //give user a unique ID $this->id = uniqid(); } } //create object Create an object $u = new User; $u->name = "Leon"; //serialize it. Note that the id attribute is not serialized during serialization. The value of id is discarded. $s = serialize($u); //unserialize it. The id is reassigned during deserialization. $u2 = unserialize( $s); //$u and $u2 have different IDs $u and $u2 have different IDs print_r($u); print_r($u2); ?>