Leo505 Leo505 - 1 year ago 83
PHP Question

Use session variable as object in PHP

Need some assistance. I am getting the following errors

Fatal error: Call to a member function getName() on string in......

This refers to the line on by


The code.


include 'classes/user.php';
$session = isset($_SESSION['userObj']) ? $_SESSION['userObj'] : "";
include 'login.php';



$user = new User();
$user->setAll($db_id,$db_fullname,$db_username,$db_rights, $db_last_login,$db);

$_SESSION['userObj'] = $user;

How do you pass objects correctly via session vars? I've checked on this site and its advised to do it like i have.

I know i'm not doing the else statement right on the
part. Should i be doing.

else{ $session = new User();}

Answer Source

Use serialize()

//Set object as session
$user = new User();
$_SESSION['userObj'] = serialize($user);

//Get object 
$user = unserialize($_SESSION['userObj']);

FYI, don't forget to write session_start(); on first line of every page to use $_SESSION.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download