Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing A PHP Object In A Session Variable

Tags:

object

php

I'm new to OOP and am writing one of my first classes. I work for an insurance broker and am trying to use a Class to store things about a quote, and store the Object as a session variable.

Thing is, when I view the session variables, I get:

sessionName         

__PHP_Incomplete_Class Object
(
    [__PHP_Incomplete_Class_Name] => myClass
    [brokerId] => 

Can anyone tell me why it's showing incomplete class name?

like image 903
Sjwdavies Avatar asked Jan 11 '10 14:01

Sjwdavies


2 Answers

Make sure that either the class definition is present before session_start() is called, e.g.

require_once 'class.MyClass.php';
session_start();

or set an unserialize_callback_func that will try to load the class definition as described at http://docs.php.net/function.unserialize.

edit: this can also be done via spl_autoload_register(). E.g.

spl_autoload_register(function($name) {
    // only a demo ...this might be insecure ;-)
  require_once 'class.'.$name.'.php';
});
session_start();
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
like image 60
VolkerK Avatar answered Oct 24 '22 05:10

VolkerK


I managed to fix it all by myself, not sure how though.

I ensured that the page displaying the values was structured like:

require_once("Class.php");
session_start();

$_SESSION['myObject']->printVariables();

And that the page constructing the object was like:

# Include the class
require_once($_SERVER['DOCUMENT_ROOT'] . "/Class.php");

# Instantiate a new policy
$_SESSION['myObject'] = new quote('54');
$_SESSION['myObject']->printVariables();

I also made sure that the page displaying calling the object did not use any serialize functions, as they seemed to only cause errors.

like image 41
Sjwdavies Avatar answered Oct 24 '22 05:10

Sjwdavies