Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...