开发者

What does serialize actually do?

开发者 https://www.devze.com 2023-03-25 03:33 出处:网络
I have read that serialize Generates a开发者_如何转开发 storable representation of a valuebut what does that mean?

I have read that serialize Generates a开发者_如何转开发 storable representation of a value but what does that mean?

What is "storable representation" here?

Can anyone provide explanation on this with an example?


It produces a string representation of the variable.

Example:

$var = array(
    'product1' => array('color' => 'red', 'size' => 'L'),
    'product2' => array('color' => 'blue', 'size' => 'M')
);
echo serialize($var);

Output:

a:2:{s:8:"product1";a:2:{s:5:"color";s:3:"red";s:4:"size";s:1:"L";}s:8:"product2";a:2:{s:5:"color";s:4:"blue";s:4:"size";s:1:"M";}}

This string can be turned back into the original multidimensional array with unserialize.


It means it is where the object/reference can be saved easily to a file, streamed, etc. then later reconstructed with the same data.

Say I have a class called Person. I'll do pseudo-C# for sake of simplicity.

class Person {
   string FirstName { get; set; }
   string LastName { get; set; }
}

I have the following Person.

var bob = new Person();
bob.FirstName = "Bob";
bob.LastName = "Smith";

Then if I serialize this as XML, I get.

<Person>
<FirstName>Bob</FirstName>
<LastName>Smith</LastName>
</Person>

At some later point, I can recreate an instance of Person that is equivalent to bob.


Take a look at:

  1. Serialization
  2. Comparison of data serialization formats
0

精彩评论

暂无评论...
验证码 换一张
取 消