Serialization can be used to convert variables including objects into continuous bytes data. You can either have a serialized variable in a file or transfer it over the network. Then crossdress the rows to revert to the original data. The classes that you define before you crossdress the objects of the class, PHP can successfully store the properties and methods of its objects. Sometimes you may need an object to be executed immediately after the crossdress is serialized. For this purpose, PHP will automatically look for __sleep and __wakeup methods.
When an object is serialized, PHP invokes the __sleep method (if one exists). After crossdress an object, PHP calls the __wakeup method. Both methods do not accept parameters. The __sleep method must return an array containing the properties that need to be serialized. PHP discards the values of other properties. If there is no __sleep method, PHP will save all properties.
Example 6.16 shows how to serialize an object using the __sleep and __wakeup methods. The id attribute is a temporary property that is not intended to be persisted in the object. The __sleep method guarantees that the ID attribute is not included in the serialized object. When crossdress a user object, the __wakeup method establishes the new value of the id attribute. This example is designed to be self-sustaining. In real-world development, you might find that objects that contain resources (like or data streams) require these methods.
Listing 6.16 Object Serialization
Class User
{
Public $name;
public $id;
function __construct ()
{
Give User a unique ID is given a different ID
$this->id = Uniqid ();
}
function __sleep ()
{
Do not serialize This->id no serialization ID
Return (Array ("name"));
}
function __wakeup ()
{
Give User a unique ID
$this->id = Uniqid ();
}
}
Create object to create a
$u = new User;
$u->name = "Leon";
Serialize it serialization note the id attribute is not serialized and the value of ID is discarded
$s = serialize ($u);
Unserialize it crossdress the row ID is re-assigned
$u 2 = unserialize ($s);
$u and $u 2 have different IDs for different IDs $u and $U2
Print_r ($u);
Print_r ($u 2);
?>
http://www.bkjia.com/PHPjc/314231.html www.bkjia.com true http://www.bkjia.com/PHPjc/314231.html techarticle Serialization can transform a variable into a continuous bytes data, including an object. You can have a serialized variable in a file or on a network. And then revert to the original number of crossdress ...