Home > Article > Backend Development > Learn how to use php serialize() and unserialize()
serialize() and unserialize() are explained in the PHP manual: serialize — Generates a storable representation of a value serialize — Produce a storable representation of a value unserialize — Creates a PHP value from a stored representation unserialize — Create a PHP value from a stored representation Obviously, the explanation of "a stored representation" is still very confusing after being translated into a storable value. Let’s take a look at the usage of these two functions through an example: name = $in_name; $this->age = $in_age; $this->owner = $in_owner; } function getage() { return ($this->age * 365); } function getowner() { return ($this->owner); } function getname() { return ($this->name); } } //实例化这个类 $ourfirstdog = new dog("Rover",12,"Lisa and Graham"); //用serialize函数将这个实例转化为一个序列化的字符串 $dogdisc = serialize($ourfirstdog); print $dogdisc; //$ourfirstdog 已经序列化为字符串 O:3:"dog":3:{s:4:"name";s:5:"Rover";s:3:"age";i:12;s:5:"owner";s:15:"Lisa and Graham";} print ' We can also change the objects in the example to other types such as arrays, and the effect will be the same! In fact, serialize() is to serialize the values of variables in PHP such as objects, arrays, etc. into strings and store them. We can store the serialized strings in other places such as databases, Sessions, etc. Cookies, etc., the serialization operation does not lose the type and structure of these values. In this way, the data of these variables can be passed between PHP pages and even different PHP programs. And unserialize() is to convert the serialized string back to a PHP value. Here is another quote from the PHP manual. After reading the above example, it should be easy to understand the meaning of the following words To change a serialized string back into a PHP value, use unserialize(). serialize() can handle any type except resource. You can even serialize() arrays that contain references to themselves. References in the array/object you are serializing() will also be stored. When serializing an object, PHP will attempt to call the object's member function __sleep() before the sequence action. This allows any cleanup operations to be done before the object is serialized. Similarly, when using unserialize() to restore an object, the __wakeup() member function will be called unserialize() operates on a single serialized variable and converts it back to a PHP value. What is returned is the converted value, which can be integer, float, string, array or object. Returns FALSE if the passed string is not deserializable. |