tags:

views:

45

answers:

3

Hi I have one page where I set up an object of class User.

$id = $_SESSION['user_id'];
$current_user =  new User();
$current_user->getFromID($id);

I've tried accessing this object from another page but it comes up blank. Is there any special way to do this?

+4  A: 

You need to save the object to the session too.

$_SESSION['user_id'] = $current_user;

Don't forget to include the User class definition (it's probably in it's own file, right?) on all pages which use the session, otherwise the User object may be corrupted.

Emil Vikström
A: 

If your object have some state, you can save it in the session.
It's the way to pass variables between scripts in PHP.

But if it doesn't - just initialize it again.

Col. Shrapnel
+2  A: 

Store the object itself in the session. To do so your object should implement __sleep() / __wakeup() functions.

Actually in this case you probably only need __wakeup(). I'd do it something like that:

User class definition:

<?php //included file
class User {
  private $user_id;
  function getFromID($id) {... doing something; }
  function __wakeup() { 
     $this->getFromID($this->user_id);
  }
}

And then using it and retrieving/storing in session;

<?php //some page
$current_user = $_SESSION['user'];
if(!$current_user) $current_user = new User();
...
$_SESSION['user'] = $current_user;
vartec
Cheers, I'm having trouble figuring out how to use these though. Any hints?
iamjonesy
ok, elaborated on that in the answer
vartec