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, and then deserialize them back to the original data. PHP can successfully store the properties and methods of a class that you define before deserializing its object. Sometimes you may need an object to be executed immediately after deserializing it. For such purposes, PHP automatically looks 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 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 values of other properties. Without the __sleep method, PHP will save all attributes.
Example 1 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 is guaranteed not to be serialized in the serialized object. Contains the id attribute. 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 objects containing resources (such as images or data streams) need these methods.
Listing1 Object serialization
class User
{
public $name;
public $id;
function __construct()
{
//give user a unique ID Give a different ID
$this->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 Serialization Note that the id attribute is not serialized, and the value of id is discarded
$s = serialize($u);
//unserialize it deserialization id is reassigned
$u2 = unserialize($s);
//$u and $u2 have different IDs $u and $u2 have different IDs ID
print_r($u);
print_r($u2);
?>