Serialization of different types

suggest change

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'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Serialization:
* Serialization of different types

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
43 Serialization
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR