Home  >  Article  >  Backend Development  >  Section 13 Object Serialization [13]_PHP Tutorial

Section 13 Object Serialization [13]_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 16:10:27867browse


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. Then deserialize and restore them to the original data. You are deserializing For a class defined before deserializing its objects, PHP can successfully store its object's properties and methods. Sometimes you may need an object to be executed immediately after deserialization. For such purposes, PHP will automatically look for __sleep and _ _wakeup method.

When an object is serialized, PHP will call the __sleep method (if it exists). After deserializing an object, PHP will call the __wakeup method. Both methods are Does not accept arguments. 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 properties.

Example 6.16 shows how 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 objects containing resources (such as images or data streams) require these methods.

Listing 6.16 Object serialization

class User
{
public $name;
public $id;

function __construct()
{
//give user a unique ID gives a different ID
$this->id = uniqid();
}

function __sleep()
{
//do not serialize this ->id does 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 Note that the id attribute is not serialized, and the value of id is discarded
$s = serialize($u);

//unserialize it The deserialization id is reassigned
$u2 = unserialize($s);

//$u and $u2 have different IDs $u and $u2 have different ID
print_r($u);
print_r($u2);
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314231.htmlTechArticleSerialization can convert variables, including objects, into continuous bytes data. You can serialize variables Store in a file or transmit over the network. Then deserialize and restore to the original data...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn