Home  >  Article  >  Backend Development  >  Serialization of objects_PHP tutorial

Serialization of objects_PHP tutorial

WBOY
WBOYOriginal
2016-07-15 13:25:00905browse

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 them and restore them to their original values. Data. For a class that you define before deserializing the object 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 deserialization. For such purposes, PHP will Automatically look for __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 attributes that need to be serialized. PHP will discard the values ​​​​of other attributes. If there is no __sleep method, PHP will save all attributes.

Example Figure 1 shows how to serialize an object using the __sleep and __wakeup methods. The Id attribute is a temporary attribute that is not intended to be retained in the object. The __sleep method guarantees 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.

Object serialization

<?php    class User    {        public $name;        public $id;        function __construct()        {            //give user a unique ID 赋予一个不同的ID            $this->id = uniqid();        }        function __sleep()        {            //do not serialize this->id 不串行化id              return(array("name"));        }        function __wakeup()        {            //give user a unique ID            $this->id = uniqid();        }    }    //create object 建立一个对象    $u = new User;    $u->name = "Leon";    //serialize it 串行化 注意不串行化id属性,id的值被抛弃    $s = serialize($u);    //unserialize it 反串行化 id被重新赋值    $u2 = unserialize($s);    //$u and $u2 have different IDs $u和$u2有不同的ID    print_r($u);    print_r($u2); ?> 

Figure 1


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/446715.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