PHP's native $_SESSION
sessions transparently serialize and unserialize objects that support PHP's serialization protocol or the Serializable
interface. You do not need to explicitly serialize them.
PHP cannot serialize resources
because these are handles to some stateful resource outside PHP's control. This is why you cannot serialize PDO
or PDOStatement
objects.
By default an object is serialized by saving all property names and values and unserialized by creating an object with the same class (without invoking the constructor) and directly setting the serialized properties. You can customize serialization behavior for your objects using the __sleep
and __wakeup
magic methods or by implementing the Serializable
interface. But not both! If you use implements Serializable
, __sleep
and __wakeup
are ignored.
One important note: when using object serialization, you must have the class definition loaded before you unserialize (or have an autoloader that can load it) and it must match the class definition of the object that was serialized. Class definitions are not stored in the serialized data.
For example suppose you have the following:
class Test {
public $version = 1;
protected $abc;
public function setAbc($abc) {
$this->abc = $abc;
}
}
$t = new Test();
$t->setAbc(123);
$_SESSION['mytest'] = $t;
Now imagine you change Test
one day to be like this instead:
class Test {
public $version = 2;
private $def;
public function setDef ($def) {
$this->def = $def;
}
}
Now suppose you load into your new code an object serialized when Test
was at version 1:
$t = $_SESSION['mytest']; // this was stored yesterday, when Test was version 1
var_dump($t)
You will get this:
object(Test)#1 (3) {
["version"]=>
int(1)
["def":"Test":private]=>
NULL
["abc":protected]=>
int(123)
}
Furthermore, you can't use old methods:
if ($t->version == 1) { // Check for class version
$t->setAbc(345); // "Fatal error: Call to undefined method Test::setAbc()"
}