Home >Backend Development >PHP Tutorial >Section 13 - Object Serialization - Classes and Objects in PHP5 [13]_PHP Tutorial
Section 13 - Object Serialization
Serialization can convert variables, including objects, into continuous bytes data. You can save the serialized variables in a file Or transmitted over the network. Then deserialize it back to the original data. For the class you define before deserializing the object of the class, PHP can successfully store the properties and methods of its object. Sometimes you may need an object Executed immediately after deserialization. For this purpose, PHP will automatically look for the __sleep and __wakeup methods.
When an object is serialized, PHP will call the __sleep method (if it exists) After deserializing an object, PHP calls the __wakeup method. Neither method accepts parameters. The __sleep method must return an array containing the properties that need to be serialized. PHP discards the values of other properties. If 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. The __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 it contains Objects of resources (such as images or data streams) require these methods.
Listing 6.16 Object serialization
<?php class User { public $name; public $id; function __construct() { //give user a unique ID 赋予一个不同的ID $this->id = uniqid(); } function __sleep() { //do not serialize this->id 不串行化id return(array("name")); } function __wakeup() { //give user a unique ID $this->id = uniqid(); } } //create object 建立一个对象 $u = new User; $u->name = "Leon"; //serialize it 串行化 注意不串行化id属性,id的值被抛弃 $s = serialize($u); //unserialize it 反串行化 id被重新赋值 $u2 = unserialize($s); //$u and $u2 have different IDs $u和$u2有不同的ID print_r($u); print_r($u2); ?>