Leo505 Leo505 - 2 months ago 15
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
index.php


$session->getName()


The code.

index.php

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

$session->getName()


login.php

session_start();
$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
isset
part. Should i be doing.

else{ $session = new User();}

Answer

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.

Comments