SoFunction
Updated on 2025-04-08

Section 13 Object serialization [13]


Serialization can convert variables including objects into continuous bytes data. You can store the serialized variables in a file or transfer them on the network. Then reverse serialization and restore them to the original data. PHP can successfully store the properties and methods of the object that you define before the object of the class that is reverse serialization. Sometimes you may need an object to be executed immediately after the reverse serialization. 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 the object is reverse serialized, 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. If there is no __sleep method, PHP will save all properties.

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 does not contain the id attribute in the serialized object. When a User object is reverse serialized, the __wakeup method creates a new value of the id attribute. This example is designed to be self-retained. In actual development, you may find that objects containing 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 Give a different ID
$this->id = uniqid();
}

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

//unserialize it reverse serialization id is reassigned
$u2 = unserialize($s);

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