I am storing my User object in a session however I am having a little trouble accessing the methods. //If the Object does not exist, create it if(!isset($_SESSION['USER'])) $_SESSION['USER'] = new User($this); //If the user is not logged in then try and log them in $_SESSION['USER']->login(); $_SESSION['USER']->save(); PHP: That above doesnt work, I would have to do this instead: $this->user = &$_SESSION['USER']; Why is this, and whats the best way of doing this?
this is what i use ob_start(); include "_admin.php"; session_start(); ob_end_flush(); $admin = new admin(); session_register('admin'); $admin->login('zeeshan', 'parvez'); $admin->make(); $admin->account->nameit(); echo '<a href="next.php">next</a>'; but i use session_register which you shouldn't You could replace that part by serializing the object and then storing it in the session array and then unserializing it on the pages where you want to see if the user is logged on or not and then access the methods.
$_SESSION is not an object, it's a simple string array, you need to serialize your objects to assign them to a session. When you serialize an object you convert it into a string, when you unserialize you convert it back to the object. // set it if(!isset($_SESSION['USER'])){ $user = new User($this); $_SESSION['USER'] = serialize($user); } // reuse it if(isset($_SESSION['USER'])){ $user = unserialize($_SESSION['USER']); if($user instanceof User){ // valid User object $user->login(); } } PHP:
Do you think SetObject() method will work? class Session { ........... public function SetObject($class_name) { if(!isset($_SESSION[$class_name])) { $num_args = func_num_args(); $params = array(); if($num_args == 1) { $obj_ins = new $class_name(); } elseif($num_args > 1) { $get_args = func_get_args(); $params = array_shift($get_args); $obj_ins = call_user_func_array(new $class_name(), $params); //$obj_ins = call_user_func_array(array($this, 'parent::__construct'), $params); } $_SESSION[$class_name] = serialize($obj_ins); } } public function GetObject($class_name) { if(isset($_SESSION[$class_name])) { $instance = unserialize($_SESSION[$class_name]); if($instance instanceof $class_name) { return $instance; } } } } $sess_handler =& new Session(); //storing class instance to session $sess_handler->SetObject('FooClass', $arg_1, $arg_2, $arg_3....etc); //getting class instance from session $foo_bar = $sess_handler->GetObject('FooClass'); $foo_bar->print_hello(); //etc PHP: