David Somekh
David Somekh

Reputation: 933

Store Object in PHP Session

In PHP, is it considered best practice to store the complete object as a session variable?

From my experience, sometimes it works and sometime not. Is there any specific reason for it?

Example:

session_start();
$object = new sample_object();
$_SESSION['sample'] = $object;

Upvotes: 8

Views: 13618

Answers (2)

tereško
tereško

Reputation: 58444

In general, the best practice is not to store objects in session at all :D

I would recommend to instead just store data. It will have the added benefit of making the debugging process a bit easier, when you have to inspect the current state of the session.

If you want to be really fancy, you could make a separate data mapper, that stores and retrieves data from the session for instances of that specific class (or group of classes, with the same interface).

Upvotes: 2

Dolly Aswin
Dolly Aswin

Reputation: 2794

Use serialize() in PHP before store your object, and call unserialize() when retrieve your object from session.

store object

session_start();
$object = new sample_object();
$_SESSION['sample'] = serialize($object);

retrieve object

session_start();
$object = unserialize($_SESSION['sample']);

Upvotes: 15

Related Questions