1

I have created an object and assigned values as follows:

$car_object =& new Car();

$car_object->offer = 'Sale'; 
$car_object->type = 'Sport Car'; 
$car_object->location = "Buffalo, New york";

How can I store the $car_object inside a session variable? How can I get the $car_object out from the session variable?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user331859
  • 51
  • 1
  • 3
  • 7

3 Answers3

6

Set to session:

$car_object = new Car();

$car_object->offer = 'Sale'; 
$car_object->type = 'Sport Car'; 
$car_object->location = "Buffalo, New york";

$_SESSION['car'] = $car_object;

Get from session:

$car_object = $_SESSION['car'];
echo $car_object->offer;
hsz
  • 148,279
  • 62
  • 259
  • 315
  • 4
    Make sure you include the class specification into the page you're unserialising the object from the session store, otherwise you'll have an object with no methods. – Nick Apr 01 '11 at 14:56
3

A more simpler way would be to do:

class SessionObject
{
    public function __construct($key)
    {
        if(isset($_SESSION[$key]))
        {
            $_SESSION[$key] = array();
        }
        $this->____data &= $_SESSION[$key];
    }

    public function __get($key)
    {
        return isset($this->___data[$key]) ? $this->___data[$key] : null;
    }

    public function __set($key,$value)
    {
        $this->___data[$key] = $value;
    }
}

Then you can use something like this;

class CarSession extends SessionObject
{
    public function __construct()
    {
        parent::__construct('car'); //name this object
    }
    /*
        * Custom methods for the car object
    */
}

$Car = new CarSession();

if(!$car->type)
{
     $Car->type = 'transit';
}

this helps for a more manageable framework for storing objects in the session.

for example:

class Currentuser extend SessionObject{}
class LastUpload  extend SessionObject{}
class UserData    extend SessionObject{}
class PagesViewed extend SessionObject{}
RobertPitt
  • 56,863
  • 21
  • 114
  • 161
1

Serializing the object and storing it into session works. Here is an entire discussion about this: PHP: Storing 'objects' inside the $_SESSION

Community
  • 1
  • 1
Jorj
  • 2,495
  • 1
  • 19
  • 12