Storing objects in PHP session

You need to use the magic __sleep and __wakeup methods for PHP 5 Objects.

For example in the following code block:

$obj = new Object();

$_SESSION['obj'] = serialize($obj);

$obj = unserialize($_SESSION['obj']);

__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.

__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.

Leave a Comment