什么是数据序列化? [英] What is data serialization ?

查看:674
本文介绍了什么是数据序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我无法从 WikiPedia 甚至没有得到清晰的定义.来自PHP手册中的序列化函数.我需要知道某些情况下需要序列化这个术语,如果没有序列化,情况会如何?换句话说,在需要序列化的地方,如果没有序列化,您的代码将缺少一些重要的功能.

First of all, I could not able to get clear definition of it from WikiPedia or even from serialize function in the PHP manual. I need to know some cases we need the term serialization and how things are going without it? In other word, Where you must need serialization and without it your code will be missing some important feature.

推荐答案

什么是序列化?

串行化将对象编码为另一种语言.
例如,您在PHP中有一个像这样的数组:

Serialization encodes objects into another language.
For example you have an array in PHP like this:

$array = array("a" => 1, "b" => 2, "c" => array("a" => 1, "b" => 2));

然后您要将其存储在文件中或发送到其他应用程序.

And then you want to store it in file or send to other application.

有几种语言选择,但是想法是相同的: 必须将该数组编码(或翻译)为文本或字节,然后才能写入文件或通过网络发送.
例如,在PHP中,如果您:

There are several language choices, but the idea is the same: The array has to be encoded (or translated), into text or bytes, that can be written to a file or sent via the network.
For example, in PHP, if you:

$data = serialize($array);

您会得到这个:

a:3:{s:1:"a";i:1;s:1:"b";i:2;s:1:"c";a:2:{s:1:"a";i:1;s:1:"b";i:2;}}

这是PHP可以理解的一种特殊的PHP序列化格式,反之亦然,因此您可以使用它来反序列化对象.
例如,您将序列化的数组存储在文件中,并希望将其作为数组返回到您的代码中:

This is PHP's particular serializing format that PHP understands, and it works vice versa, so you are able to use it to deserialize objects.
For example, you stored a serialized array in a file, and you want it back in your code as an array:

$array = unserialize($data);

但是您可以选择其他序列化格式,例如JSON:

But you could choose a different serialization format, for example, JSON:

$json = json_encode($array);

会给你这个:

{"a":1,"b":2,"c":{"a":1,"b":2}}

结果不仅易于保存,人眼读取或通过网络发送,而且几乎对所有其他语言(JavaScript,Java,C#,C ++等)也可以理解

The result is not only easily saved, read by human eye, or sent via network, but is also understandable to almost every other language (JavaScript, Java, C#, C++, ...)

结论
序列化会将对象翻译成另一种语言,以防您要存储或共享数据.

Conclusion
Serialization translations objects to another language, in case you want to store or share data.

是否有什么情况,您只能执行序列化而不能执行任何操作?

不.但是序列化通常会使事情变得更容易.

No. But serialization usually makes things easier.

JSON和PHP格式是否是唯一可能的格式?
不,不,不,再没有一次.格式很多.

Are JSON and PHP format the only possible formats?
No, no, no and one more time no. There are plenty of formats.

  • 具有SOAP,WSDL等(具有特定用途)的后继者的XML
  • 字节
  • ...
  • ...
  • ...
  • 您自己的格式(您可以创建自己的格式进行序列化并使用它,但这通常是一件大事,不值得这样做)

这篇关于什么是数据序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆