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

后端 未结 4 597
时光取名叫无心
时光取名叫无心 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: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();
    

提交回复
热议问题