开发者

Don't understand serialize()

开发者 https://www.devze.com 2022-12-16 03:31 出处:网络
I\'m lookin开发者_如何学运维g at this function: serialize() for PHP and I don\'t really understand what is it\'s function. Can someone provide a simple example with output? Basically, the goal of seri

I'm lookin开发者_如何学运维g at this function: serialize() for PHP and I don't really understand what is it's function. Can someone provide a simple example with output?


Basically, the goal of serialize is to transform any (alsmost) kind of data to a string, so it can be transmitted, stored, ...

A quick example :

$my_array = array(
    'a' => 10,
    'glop' => array('test', 'blah'),
);
$serialized = serialize($my_array);
echo $serialized;

Will get you this output :

a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}


And, later, you can unserialize that string, to get the original data back :

$serialized = 'a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}';
$data = unserialize($serialized);
var_dump($data);

Will get you :

array
  'a' => int 10
  'glop' => 
    array
      0 => string 'test' (length=4)
      1 => string 'blah' (length=4)


Common uses include :

  • Ability to transmit (almost) any kind of PHP data from one PHP script to another
  • Ability to store (almost) any kind of PHP data in a single database field -- even if it's not quite a good practice on the database-side, it can sometimes be usefull
  • Ability to store data in some caching mecanism (APC, memcached, files, ...), in which you can only store strings

Note, though, that using serialize is great when you are only working with PHP (as it's a PHP-specific format, that's able to work with almost any kind of PHP data, and is really fast) ; but it's not that great when you have to also work with something else than PHP (as it's PHP-specific). In those cases, you can use XML, JSON (see json_encode and json_decode), ...


In the PHP manual, you can also read the Object Serialization section, btw.


If you want to save an array or object normalised in a database row for example, serialize() (and unserialize()) are your friends, because you can't store an array or object flattened without first turning it into a string.

json_encode() and json_decode() are similar except they encode as JSON.


See this example, should be pretty clear.

0

精彩评论

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