开发者

How can I store object class into a session in PHP?

开发者 https://www.devze.com 2023-02-22 22:20 出处:网络
How can I have an object class store into PHP session and then get it in my next page as variable. Could you help?

How can I have an object class store into PHP session and then get it in my next page as variable. Could you help?

Here is my class.inc.php

class shop {

var $shoeType;
var $color;

 开发者_高级运维   public function __construct() {

        $shoeTypeService = new ShoeTypeService();
        $shoe = $shoeTypeService->getAllShoes();
        $this->shoeType = $shoe[20];
    }
}


Once you instantiate the class you can assign it to the session (assuming it's started)

$_SESSION['SomeShop'] = new Shop();

or 

$Shop = new Shop();
//stuff
$_SESSION['SomeShop'] = $Shop;

Keep in mind that wherever you access that object you will need the Shop Class included.


used this code first page

$obj = new Object();

$_SESSION['obj'] = serialize($obj);

in second page

$obj = unserialize($_SESSION['obj']);


You cannot simply store an object instance into the session. Otherwise the object will not be appeared correctly in your next page and will be an instance of __PHP_Incomplete_Class. To do so, you need to serialize your object in the first call and unserialize them in the next calls to have the object definitions and structure all intact.


Extending on Jakes answer It can be done with very little hassle like everything in php. Here is a test case:

session_start();

$_SESSION['object'] = empty($_SESSION['object'])? (object)array('count' => 0) : $_SESSION['object'];
echo $_SESSION['object']->count++;

It will output count increased by 1 on every page load. However you will have to be careful when you first initiate the $_SESSION variable to check whether it is already set. You dont want to over write the value everytime. So be sure to do:

if (empty($_SESSION['SomeShop']))
    $_SESSION['SomeShop'] = new Shop();

or better yet:

if (!$_SESSION['SomeShop'] instanceof Shop)
    $_SESSION['SomeShop'] = new Shop();
0

精彩评论

暂无评论...
验证码 换一张
取 消