Reputation: 51
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?
Upvotes: 1
Views: 6188
Reputation: 57268
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{}
Upvotes: 3
Reputation: 2691
Serializing the object and storing it into session works. Here is an entire discussion about this: PHP: Storing 'objects' inside the $_SESSION
Upvotes: 1
Reputation: 152216
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;
Upvotes: 6