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
  • 193,403
  • 52
  • 435
  • 836
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

12

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,471
  • 15
  • 24
9

used this code first page

$obj = new Object();

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

in second page

$obj = unserialize($_SESSION['obj']);
Shakti Patel
  • 3,762
  • 4
  • 22
  • 29
  • 1
    Does not work, it still says "__PHP_Incomplete_Class_Name" in the unserialized object. – Black Sep 13 '19 at 12:21
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,188
  • 6
  • 31
  • 29