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 thi开发者_如何学JAVAs object from another page but it comes up blank. Is there any special way to do this?
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.
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;
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.
精彩评论