Serializes objects. Serializing variables, including objects, can be converted into continuous bytes data. you can save serialized variables in a file or transmit them over the network. then, the deserialization is restored to the original number serialization. variables including objects can be converted into continuous bytes data. you can save serialized variables in a file or transmit them over the network. then, the data is deserialized and restored to the original data. PHP can successfully store the attributes and methods of the objects defined before the objects of the deserialization class. sometimes you may need an object to be executed immediately after deserialization. for this purpose, PHP will automatically find the _ sleep and _ wakeup methods.
When an object is serialized, PHP calls the _ sleep method (if any ). after an object is deserialized, PHP calls the _ wakeup method. both methods do not accept parameters. the _ sleep method must return an array containing the attributes to be serialized. PHP will discard other attribute values. if the _ sleep method is not available, PHP will save all attributes.
The example shows how to serialize an object using the _ sleep and _ wakeup methods. the Id attribute is a temporary attribute not intended to be retained in the object. the _ sleep method ensures that the id attribute is not included in the serialized object. when a User object is deserialized, the __wakeup method creates a new value for the id attribute. this example is designed to be self-sustaining. in actual development, you may find that objects containing resources (such as or data streams) need these methods.
Object serialization
<? Php class User {public $ name; public $ id; function _ construct () {// give user a unique ID to assign a different ID $ this-> id = uniqid ();} function _ sleep () {// do not serialize this-> id is not serialized id return (array ("name");} function _ wakeup () {// give user a unique ID $ this-> id = uniqid () ;}// create an object $ u = new User; $ u-> name = "Leon"; // serialize it serializization note that the id attribute is not serialized, and the id value is discarded $ s = serialize ($ u); // unser Ialize it deserialization id is assigned $ u2 = unserialize ($ s ); // $ u and $ u2 have different IDs $ u and $ u2 have different IDs print_r ($ u); print_r ($ u2);?> |
Summary. you can save the serialized variable in a file or transmit it over the network. then, the variable is deserialized to the original number...