我可以在$ _SESSION空间中存储类实例吗? [英] Can I store a class instance in a $_SESSION space?

查看:154
本文介绍了我可以在$ _SESSION空间中存储类实例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类用户{

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

public function __construct($ username,$ email,$ password,$ id,$ active,$ donator,$ steam){
$ this-> id = $ id;
$ this-> username = $ username;
$ this-> password = $ password;
$ this-> email = $ email;
$ this-> steam = $ steam;
$ this-> donator = $ donator;
$ this-> active = $ active;
}}

是我的课程(简化)



以下是我的代码:

  $ _ SESSION ['loggedIn'] = $ user; 

$ user是用户的类实例



现在这是print_r($ _ SESSION ['loggedIn'])显示我:

  __PHP_Incomplete_Class Object 

[__PHP_Incomplete_Class_Name] => User
[id] => 22
[username] => xxxx
[password] => xxxx
[email ] => xxxx
[steam] => 1234567
[donator] => 0
[活动] => 1



其中xxxx是正确的值。



从我的会话检索数据。像这样:$ _SESSION ['loggedIn'] - > username它返回一个null值给我。

解决方案

首先将对象序列化为字符串:



$ _ SESSION ['user'] = serialize($ user);



和:



$ user = unserialize($ _ SESSION ['user' ]);



只要确保在反序列化对象之前首先定义类。


 Class User{

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

public function __construct($username, $email, $password, $id, $active, $donator, $steam){
    $this->id = $id;
    $this->username = $username;
    $this->password = $password;
    $this->email = $email;
    $this->steam = $steam;
    $this->donator = $donator;
    $this->active = $active;
}}

is my class (simplified)

the following is my code:

$_SESSION['loggedIn'] = $user;

$user is a class instance of User

now this is what print_r($_SESSION['loggedIn']) shows me:

    __PHP_Incomplete_Class Object
(
    [__PHP_Incomplete_Class_Name] => User
    [id] => 22
    [username] => xxxx
    [password] => xxxx
    [email] => xxxx
    [steam] => 1234567
    [donator] => 0
    [active] => 1
)

in which xxxx are values that are correct.

but when i try to retrieve data from my session. like so: "$_SESSION['loggedIn']->username" it returns a null value to me.

解决方案

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.

这篇关于我可以在$ _SESSION空间中存储类实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆