php5| objects can be serialized to include the object, into the continuous bytes data, you can have serialized variables in a file or on the network, and then drag the row to revert to the original data. You drag the class defined before the object of the row class, PHP can successfully store its object's properties and methods. Sometimes you may need an object to execute immediately after drag. For this purpose, PHP will automatically look for __sleep and __wakeup methods.
When an object is serialized, PHP invokes the __sleep method (if it exists). After drag an object, PHP invokes the __wakeup method. Neither of these methods accepts parameters. The __sleep method must return an array containing the attributes that need to be serialized. PHP discards the values of other attributes. If there is no __sleep method, PHP will save all properties.
Example 1 shows how to serialize an object using the __sleep and __wakeup methods. The ID property is a temporary property that is not intended to remain in the object. The __sleep method guarantees that no ID attribute is included in the serialized object. When the drag rows a user object, the __wakeup method creates a new value for the id attribute. This example is designed to maintain itself. In actual development, you may find that objects that contain resources, such as images or data flows, require these methods.
Listing1 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 the ID is discarded
$s = serialize ($u);
Unserialize It drag the row ID is assigned a value
$u 2 = unserialize ($s);
$u and $u 2 have different IDs $u and $U2 have different IDs
Print_r ($u);
Print_r ($u 2);
? >
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.