在PHP会话中存储对象 [英] Storing objects in PHP session

查看:95
本文介绍了在PHP会话中存储对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP文档说:您不能在会话变量中使用引用,因为没有可行的方法来还原对另一个变量的引用."

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;

我尝试在会话中存储一个简单的字符串和一个User对象,该字符串在页面之间或页面刷新后始终存在.但是,User变量在$ _SESSION中丢失(变为空).

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).

有什么主意吗?

在&之前,我已经确认所有这些页面/子页面中的session_id都相同.页面刷新后.

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

奇怪的是,在我尝试了下面的序列化和反序列化方法之后,会话中的序列化用户对象(或字符串)仍然消失了!

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

最终,我弄清了错误所在,看起来$ _SESSION ['user']被某种神秘的力量所覆盖,如果我使用'user'以外的任何变量,那么一切都很好.当您将对象放入$ _SESSION时,PHP(我正在使用的版本至少为5.3)会自动进行序列化和反序列化.

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; 

推荐答案

您需要使用例如在以下代码块中:

$obj = new Object();

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

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

__ sleep由serialize()调用. sleep方法将从您要保留的对象中返回值的数组.

__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.

__ wakeup由unserialize()调用.唤醒方法应采用未序列化的值,然后在对象中的值中对其进行初始化.

__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.

这篇关于在PHP会话中存储对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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