Can I store a class instance in a $_SESSION space?

前端 未结 4 1072
广开言路
广开言路 2020-12-10 13:22
 Class User{

public $id;
public $username;
public $password;
public $email;
public $steam;
public $donator;
public $active;

public function __construct($username,          


        
相关标签:
4条回答
  • 2020-12-10 13:49

    You can store objects in $_SESSION. PHP will serialize them for you. Just make sure the class is defined before calling session_start, or that it can be autoloaded. The reason the value stored in the session has type "__PHP_Incomplete_Class_Name" is that the User class wasn't defined when the object was unserialized during session loading (as explained in the PHP manual page on object serialization).

    Resources can't be serialized. If you ever store an object that uses resources, implement __sleep and __wakeup to customize the serialization. PHP's serialization should be able handle all other types, even if they contain circular references.

    0 讨论(0)
  • 2020-12-10 13:57

    While on the same page, the session variable acts like just another vairable, so you can do with it what you want. THat's why you can store the object while still on that page.

    Retrieving it later will actually show if it is fit for a session, which it is not in your case.

    If you really need to save that object, you could try and save it as a serialized object, and unserialize it after retrieval. That should work, although I don't know if this is the best sollution / design. Passing objects around like this might be considered a bit...anti-pattern

    0 讨论(0)
  • 2020-12-10 14:12

    You must first serialize the object in to a string:

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

    and:

    $user = unserialize($_SESSION['user']);

    Just make sure that the class is first defined before unserializing the object.

    0 讨论(0)
  • 2020-12-10 14:12

    $_SESSION variables seem to be only able to store arrays, numbers, and strings.

    They cannot store a class object after you change to a new page.

    0 讨论(0)
提交回复
热议问题