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?

1
  • Why do you want to store it as a session variable? Commented Apr 1, 2011 at 14:47

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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{}

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.