Search code examples
phpserializationrepresentationstorable

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()

I understood that serialize() is used to generate a storable representation of a value which is passed to it.

I think it means serialize() converts the received value into some string using its internal functionality. Is this my perception right about 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. Also, I'm not able to understand how this output is formed by 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?

Please guide me in this regard.


Solution

  • 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. I hope this helps.