在 2 个 php 脚本之间传递 $_SESSION 中的对象
可能的重复:
PHP:在 $_SESSION 中存储“对象”
我有 2 个脚本文件,名为“search.php”和“share.php”,我想将信息从第一个发送到第二个。我创建了一个名为 $_SESSION['search'] 的变量,它是 Search 类的对象,但我无法读取第二个脚本文件中的对象。
search.php
session_start();
$_SESSION['search'] = new Search($text);
(...)
share.php
session_start();
$itemList = $_SESSION['search']->getItemList(); // Error
为什么?如何在 PHP 中将信息从一个脚本传递到另一个脚本?
Possible Duplicate:
PHP: Storing 'objects' inside the $_SESSION
I have 2 scripts files named 'search.php' and 'share.php' and I want to send information from the first to the second one. I created a var named $_SESSION['search'] wich is a object of the class Search, but I can't read the object in the second script file.
search.php
session_start();
$_SESSION['search'] = new Search($text);
(...)
share.php
session_start();
$itemList = $_SESSION['search']->getItemList(); // Error
Why? How can I pass info from one script to another in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您要使用会话传递变量,那么您需要将变量添加到 search.php 中的会话中,如下所示:
然后将变量返回到 share.php 中,如下所示:
如果您遇到问题,我会检查“新搜索($文本);”在第一页上,并确保它是您真正想要存储的开始内容。
If you are going to pass the variable using sessions then you need to add the variable to the session in search.php like so:
And then get the variable back out in share.php like so:
If you are having problems I would check "new Search($text);" on the first page and be sure that it is what you actually want stored to begin with.
PHP 自动序列化会话中的对象。
您不能在该对象中拥有任何作为资源的成员(即数据库连接等)。如果您需要它们,您需要将 __sleep 和 __wake 方法添加到您希望存储在会话中的对象中。 __sleep 将 obj 渲染为值 obj (实际上是一个数组,因为您必须返回一个数组),并且 __wake 方法应该基于该数组重建 obj。
阅读此
PHP automagically serializes objects in a session.
You CANNOT have any members in that object that are resources (ie a db connection etc.). If you need them in there you need to add __sleep and __wake methods to the object you wish to store in the session. __sleep renders the obj as a value obj (an array actually as you must return an array) and the __wake method should reconstruct the obj based on that array.
read this
也许您只是缺少包含
Search
类的 php 文件。如果在从会话中反序列化对象时不知道该类,则 PHP 会创建一个“虚拟”对象,仅包含属性,但不了解其方法。如果包含该类,那么 PHP 可以将其反序列化为该类的真实对象。
Maybe you are only missing an include of your php file containing the
Search
class.If the class is not known at the moment you deserialize the object from the session, then PHP makes a "dummy" object, only containing the attributes, but without knowledge about it's methods. If you include the class, then PHP can deserialize it to a real object of this class.