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

后端 未结 4 593
时光取名叫无心
时光取名叫无心 2021-01-19 21:21

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 sho         


        
相关标签:
4条回答
  • 2021-01-19 21:41

    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.

    0 讨论(0)
  • 2021-01-19 21:47

    used this code first page

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

    in second page

    $obj = unserialize($_SESSION['obj']);
    
    0 讨论(0)
  • 2021-01-19 21:49

    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 讨论(0)
  • 2021-01-19 21:54

    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 讨论(0)
提交回复
热议问题