Storing objects in PHP session

后端 未结 5 2148
悲&欢浪女
悲&欢浪女 2020-11-29 02:24

The PHP documentation says \"You can\'t use references in session variables as there is no feasible way to restore a reference to another variable.\"

Does this mean

5条回答
  •  囚心锁ツ
    2020-11-29 03:01

    You need to use the magic __sleep and __wakeup methods for PHP 5 Objects.

    For example in the following code block:

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

    __sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.

    __wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.

提交回复
热议问题