5

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];
    }
}
hakre
  • 184,866
  • 48
  • 414
  • 792
mary
  • 149
  • 1
  • 5
  • 10
  • 1
    This question has already been asked and received a comprehensive answer. Check it out: http://stackoverflow.com/questions/871858/php-pass-variable-to-next-page/872522#872522 – Oren Hizkiya Apr 07 '11 at 09:14

4 Answers4

11

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.

Jake
  • 2,431
  • 14
  • 23
8

used this code first page

$obj = new Object();

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

in second page

$obj = unserialize($_SESSION['obj']);
Shakti Patel
  • 3,570
  • 4
  • 20
  • 29
3

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.

0

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();
shxfee
  • 5,008
  • 5
  • 30
  • 28