iamjonesy
iamjonesy

Reputation: 25132

Using Objects throughout application

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?

Upvotes: 3

Views: 82

Answers (3)

vartec
vartec

Reputation: 134671

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;

Upvotes: 2

Your Common Sense
Your Common Sense

Reputation: 157916

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.

Upvotes: 0

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91983

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.

Upvotes: 4

Related Questions