Serialize: PHP's Serialization Format
Serialize: PHP's Serialization Format
Serialize: PHP's Serialization Format
This is useful for storing or passing PHP values around without losing their type and
structure.
Note:
Object's private members have the class name prepended to the member name;
protected members have a '*' prepended to the member name. These prepended
values have null bytes on either side.
You probably already know how the output of serialize() roughly looks like: It has
some kind of type specifier (like s or i), followed by a colon, followed by the actual data,
followed by a semicolon. As such the serialization format for the “simple” types looks as
follows:
NULL: N;
true: b:1;
false: b:0;
42: i:42;
42.3789: d:42.378900000000002;
"foobar": s:6:"foobar";
^-- strlen("foobar")
resource: i:0;
^-- Resources can't really be serialized, so they just get the
value int(0)
For objects there are two serialization mechanisms: The first one simply serializes the
object properties just like it is done for arrays. This mechanism uses O as the type
specifier.
<?php
class Test {
public $public = 1;
protected $protected = 2;
private $private = 3;
O:4:"Test":3:{s:6:"public";i:1;s:12:"\0*\0protected";i:2;s:13:"\0Test\
0private";i:3;}
The second mechanism allows for custom serialization formats. It delegates the actual
serialization to the serialize method of the Serializable interface and uses
the C type specifier. For example consider this class:
<?php
return "foobar";
// ...
C:5:"Test2":6:{foobar}
^-- strlen("foobar")
Introduction
Note, that when an old instance of a class that implements this interface now, which had
been serialized before the class implemeted the interface, is unserialized, __wakeup() is
called instead of the serialize method, what might be useful for migration purposes.
Interface synopsis
Serializable {
/* Methods */
abstract public string serialize ( void )
abstract public void unserialize ( string $serialized )
<?php
class obj implements Serializable {
private $data;
public function __construct() {
$this->data = "My private data";
}
public function serialize() {
return serialize($this->data);
}
public function unserialize($data) {
$this->data = unserialize($data);
}
public function getData() {
return $this->data;
}
}
$obj = new obj;
$ser = serialize($obj);
var_dump($ser);
$newobj = unserialize($ser);
var_dump($newobj->getData());
?>