You can use $_SESSION to store the object, and serialize to convert to
string and reverse

// file one.php
require 'user.php';
$user = new User();
$_SESSION[ 'user' ] = serialize( $user );

// file two.php
require 'user.php';   // the class needs to be declared
$user = unserialize( $_SESSION[ 'user' ] );

I think this is the cleanest way to do, but no the best performant.
If you need performance you can use the interface serializable

If you need a resources (like a db connection) you can implement __sleep and
__wakeup in your class

On Wed, Jun 17, 2009 at 12:11 AM, James Colannino <>wrote:

> Hey everyone,
> Long time reader, not such a long time poster :-P (though I have posted
> to the list occasionally in the past...)
> Anyway, I have a general question for the list.  Basically, I need to
> maintain persistent objects between page refreshes.  So, for example, if
> while running a PHP script the first time I create an instance of class
> foo, the next time the script is run (when the browser reloads the page)
> I can again access that same instance of foo.
> I know that there's no way to truly do that, since a script only runs
> while generating output for the browser, but my question is, in the
> group's opinion, what's the best way to mimic this sort of behavior
> using temporary storage?  Should I be using temporary files?
> I can think of at least a couple ways to do it, but I'd like to get some
> opinions as to "best practice" techniques, which take both security and
> relative efficiency into account.  I would want to make sure that data
> isn't shared between multiple concurrent sessions, which would be a bad
> thing for what I'm doing.  my oh-so-limited knowledge of PHP is shining
> through, I think :)
> Thanks so much!
> James
> --
> PHP General Mailing List (
> To unsubscribe, visit:

Martin Scotta

Reply via email to