Home  >  Article  >  Backend Development  >  The difference between php serialization functions

The difference between php serialization functions

王林
王林Original
2019-09-16 17:54:092056browse

The difference between php serialization functions

serialize() //把变量和它们的值编码成文本形式,即产生一个可存储的值的表示

Detailed explanation:

##serialize() Returns a string, this string contains A byte stream representing value, which can be stored anywhere. This facilitates storing or passing PHP values ​​without losing their type and structure.

unserialize() //恢复原先变量。

Detailed explanation:

unserialize() Operate on a single serialized variable and convert it Returns the value to PHP. If the passed string is not deserializable, returns FALSE and produces an E_NOTICE.

$arr=array();
$arr['name']='张三';
$arr['age']='22';
$arr['sex']='男';
$arr['phone']='123456789';
$arr['address']='上海市浦东新区';
var_dump($arr);

//输出:
//  array(5) { 
//  ["name"]=> string(6) "张三"
//  ["age"]=> string(2) "22"
//  ["sex"]=> string(3) "男"
//  ["phone"]=> string(9) "123456789"
//  ["address"]=> string(21) "上海市浦东新区"
//   }

//序列化:
$info=serialize($arr);
var_dump($info);

//输出:
//string(140) "a:5:{s:4:"name";s:6:"张三";s:3:"age";s:2:"22";s:3:"sex";s:3:"男";s:5:"phone";s:9:"123456789";s:7:"address";s:21:"上海市浦东新区";}"

   ////////////////////////说明/////////////////////////////////
//**a:5标志序列化为array包含5个键值对,s:4标志内容为字符串包含4个字符。**//


$zhangsan=unserialize($info);
var_dump($zhangsan);

//输出:
//  array(5) { 
//  ["name"]=> string(6) "张三"
//  ["age"]=> string(2) "22"
//  ["sex"]=> string(3) "男"
//  ["phone"]=> string(9) "123456789"
//  ["address"]=> string(21) "上海市浦东新区"
//   }

If you want to change the serialized string back into a PHP value, you can 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 an object is restored using unserialize(), the __wakeup() member function will be called.

The above content is for reference only!

Recommended tutorial:

PHP video tutorial

The above is the detailed content of The difference between php serialization functions. For more information, please follow other related articles on the PHP Chinese website!

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