Reputation: 933
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
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
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