Saving Object in Session

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

I've been doing stuff like:

<?php
$_SESSION
['user'] = new User(blah, blah);
?>

in my code for a while now. Is there anything wrong with saving an object in a session? I have yet to find a drawback to it, but maybe I'm overlooking something...

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

In other languages, the objects had to be serializable, I think. In PHP, I think as long as the object isn't anything to do with something instance-based, like a MySQL connection, you're fine.

Does your object just have values, or are there any methods?

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

Methods (most of them could be removed since they are just accessors) and values. Why do you ask?

And if you're not putting objects in sessions, how do you manage state data (besides putting each piece of data into a separate session var)? Are you manually serializing it? Are you keeping everything in a database with the sessionID as the primary key?

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

I'm not sure why you would want to store an object with methods. I sometimes store profile information (user id, email, whatever) in the session, but it would be an assoc array or data object.

All other things I store are just variables.

JeevesBond's picture

He has: 3,956 posts

Joined: Jun 2002

This is one of those subjects where I'd like to hear Abhi's opinion too. Smiling

Serialising methods isn't harmful, but storing a whole user class instance is a little inefficient. Most user state information should already be recorded in the database, pretty-much all you need in $_SESSION is the user id, a datestamp of when they performed their last action (if you want a who's online widget), and other stuff relating to just this session, a message to display to the user, for example.

I tried this out myself, and PHP sensibly just stored the object's state, i.e. it guessed what I wanted and did it. So, what you're doing is convenient, but it is possibly storing a little more information than you need. Smiling

a Padded Cell our articles site!

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.