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
406 views
in Technique[技术] by (71.8m points)

Storing objects in PHP session

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 I can't have things like:

session_start();
$user = new User;
$user->name = 'blah';
$_SESSION['user'] = $user;

I have tried to store a simple string and a User object in session, the string always persists between pages to pages, or after page refresh. However the User variable is lost in $_SESSION(becomes empty).

any idea?

Edit: I have confirmed that session_id is the same in all of these pages/subpages,before & after page refresh.

Edit: Strangely, after I tried serialize and unserialize approach below, the serialized user object(or string) in session still still disappears!

Edit: finally I figured out what the bug was, looks like somehow $_SESSION['user'] gets overwritten by some mysterious force, if I use any variable other than 'user', then everything's fine. PHP(at least 5.3 which is the version I'm using) does serialize and unserialize automatically when you put object in the $_SESSION.

session_start();
$user = new User();
$user->name = 'blah'
$_SESSION['myuser'] = $user; 
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


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

...