简体   繁体   English

作为PHP开发人员,我是否有必要了解serialize()生成值的可存储表示的方式?

[英]As a PHP developer, is it necessary for me to understand the way serialize() generates the storable representation of a value?

I'm using PHP 7.1.12 and I'm trying to understand the functionality of one of the most important built-in functions in PHP serialize() 我正在使用PHP 7.1.12,并且试图了解PHP serialize()最重要的内置函数之一的功能。

I understood that serialize() is used to generate a storable representation of a value which is passed to it. 我知道serialize()用于生成传递给它的值的可存储表示。

I think it means serialize() converts the received value into some string using its internal functionality. 我认为这意味着serialize()使用其内部功能将接收到的值转换为某些字符串。 Is this my perception right about serialize() ? 我对serialize()看法正确吗?

Consider below code : 考虑下面的代码:

<?php

$a = [];
$a[] = $a;
echo "\na: ".serialize($a);

$b = [];
$b[] =& $b;
echo "\nb: ".serialize($b);

Output : 输出:

a: a:1:{i:0;a:0:{}}
b: a:1:{i:0;a:1:{i:0;R:2;}}

In the output I'm not able to understand from where the letters i, a, R are coming into the output. 在输出中,我无法理解字母i,a,R从何处进入输出。 Also, I'm not able to understand how this output is formed by serialize() 此外,我不明白此输出是如何由serialize()形成的

So, my question is; 所以,我的问题是; As a PHP developer, is it necessary for me to understand above output or should I directly make use of this output without going into the details of it? 作为PHP开发人员,我是否有必要了解上面的输出,还是我应该直接使用此输出而不进行详细说明?

Please guide me in this regard. 请在这方面指导我。

The below is the general explanation of what those characters mean. 以下是这些字符含义的一般说明。

String

s:size:value;

Integer 整数

i:value;

Boolean 布尔型

b:value; (store '1' or '0')

Null 空值

N;

Array 数组

a:size:{key definition;value definition;(repeated per element)}

Object 宾语

O:strlen(object name):object name:object size:{s:strlen(property name):property name:property definition;(repeated per property)}

It is not really necessary for us to know, how PHP serializes, but if you are are curious, the above explanation would help to understand that there is some logic to it. 对于我们来说,实际上并不需要知道PHP如何序列化,但是如果您很好奇,上面的解释将有助于您了解其中有一些逻辑。 I hope this helps. 我希望这有帮助。

Another feature of PHP's serialization format is that it will properly preserve references: The important part here is the R:2; PHP的序列化格式的另一个功能是,它将正确保留引用:这里重要的部分是R:2; element. 元件。 It means “reference to the second value. 意思是“参考第二个值。 As objects in PHP exhibit a reference-like behavior serialize also makes sure that the same object occurring twice will really be the same object on unserialization: 由于PHP中的对象表现出类似引用的行为,因此序列化还可以确保发生两次序列化的同一对象实际上是反序列化时的同一对象:

$b = [];
$b[] =& $b;
echo "\nb: ".serialize($b);

output:b: a:1:{i:0;a:1:{i:0;R:2;}}

The whole array is the first value, the first index is the second value, so that's what is referenced. 整个数组是第一个值,第一个索引是第二个值,因此被引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM