我创建了一个对象,并按如下方式赋值:
$ car_object =&新车();
$car_object->offer = 'Sale';
$car_object->type = 'Sport Car';
$car_object->location = "Buffalo, New york";
如何将$ car_object存储在会话变量中? 如何从会话变量中获取$ car_object?
答案 0 :(得分:5)
设置为会话:
$car_object = new Car();
$car_object->offer = 'Sale';
$car_object->type = 'Sport Car';
$car_object->location = "Buffalo, New york";
$_SESSION['car'] = $car_object;
从会话中获取:
$car_object = $_SESSION['car'];
echo $car_object->offer;
答案 1 :(得分:3)
更简单的方法是:
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;
}
}
然后你可以使用这样的东西;
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';
}
这有助于在会话中存储对象的更易管理的框架。
例如:
class Currentuser extend SessionObject{}
class LastUpload extend SessionObject{}
class UserData extend SessionObject{}
class PagesViewed extend SessionObject{}
答案 2 :(得分:0)
序列化对象并将其存储到会话中。以下是对此的完整讨论:PHP: Storing 'objects' inside the $_SESSION