Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

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

 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...