PHP Serialization of different types


Example

Generates a storable representation of a value.

This is useful for storing or passing PHP values around without losing their type and structure.

To make the serialized string into a PHP value again, use unserialize().

Serializing a string

$string = "Hello world";    
echo serialize($string);

// Output: 
// s:11:"Hello world";

Serializing a double

$double = 1.5;    
echo serialize($double);

// Output: 
// d:1.5;

Serializing a float

Float get serialized as doubles.

Serializing an integer

$integer = 65;    
echo serialize($integer);

// Output: 
// i:65;

Serializing a boolean

$boolean = true;    
echo serialize($boolean);

// Output: 
// b:1;

$boolean = false;    
echo serialize($boolean);

// Output: 
// b:0;

Serializing null

$null = null;    
echo serialize($null);

// Output: 
// N;

Serializing an array

$array = array(
    25,
    'String',
    'Array'=> ['Multi Dimension','Array'],
    'boolean'=> true,
    'Object'=>$obj, // $obj from above Example
    null,
    3.445
); 


// This will throw Fatal Error
// $array['function'] = function() { return "function"; };

echo serialize($array);

// Output:
// a:7:{i:0;i:25;i:1;s:6:"String";s:5:"Array";a:2:{i:0;s:15:"Multi Dimension";i:1;s:5:"Array";}s:7:"boolean";b:1;s:6:"Object";O:3:"abc":1:{s:1:"i";i:1;}i:2;N;i:3;d:3.4449999999999998;}

Serializing an object

You can also serialize Objects.

When serializing objects, PHP will attempt to call the member function __sleep() prior to serialization. This is to allow the object to do any last minute clean-up, etc. prior to being serialized. Likewise, when the object is restored using unserialize() the __wakeup() member function is called.

class abc {
    var $i = 1;
    function foo() {
        return 'hello world';
    }
}

$object = new abc(); 
echo serialize($object);

// Output:
// O:3:"abc":1:{s:1:"i";i:1;} 

Note that Closures cannot be serialized:

$function = function () { echo 'Hello World!'; };
$function(); // prints "hello!"

$serializedResult = serialize($function);  // Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'Closure' is not allowed'