如何在 PHP 中将对象类存储到会话中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5578679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I store object class into a session in PHP?
提问by mary
How can I have an object class store into PHP session and then get it in my next page as variable. Could you help?
如何将对象类存储到 PHP 会话中,然后在下一页中将其作为变量获取。你能帮忙吗?
Here is my class.inc.php
这是我的 class.inc.php
class shop {
var $shoeType;
var $color;
public function __construct() {
$shoeTypeService = new ShoeTypeService();
$shoe = $shoeTypeService->getAllShoes();
$this->shoeType = $shoe[20];
}
}
回答by Jake
Once you instantiate the class you can assign it to the session (assuming it's started)
实例化类后,您可以将其分配给会话(假设它已启动)
$_SESSION['SomeShop'] = new Shop();
or
$Shop = new Shop();
//stuff
$_SESSION['SomeShop'] = $Shop;
Keep in mind that wherever you access that object you will need the Shop Class included.
请记住,无论您在何处访问该对象,都需要包含 Shop 类。
回答by Shakti Patel
used this code first page
使用此代码第一页
$obj = new Object();
$_SESSION['obj'] = serialize($obj);
in second page
在第二页
$obj = unserialize($_SESSION['obj']);
回答by Taha Kamkar
You cannot simply store an object instance into the session. Otherwise the object will not be appeared correctly in your next page and will be an instance of __PHP_Incomplete_Class. To do so, you need to serializeyour object in the first call and unserializethem in the next calls to have the object definitions and structure all intact.
您不能简单地将对象实例存储到会话中。否则该对象将不会在您的下一页中正确显示,而是 __PHP_Incomplete_Class 的一个实例。为此,您需要在第一次调用中序列化您的对象,并在下一次调用中将它们反序列化,以使对象定义和结构完整无缺。
回答by shxfee
Extending on Jakes answer It can be done with very little hassle like everything in php. Here is a test case:
扩展 Jakes 的答案 它可以像 php 中的所有内容一样轻松完成。这是一个测试用例:
session_start();
$_SESSION['object'] = empty($_SESSION['object'])? (object)array('count' => 0) : $_SESSION['object'];
echo $_SESSION['object']->count++;
It will output count increased by 1 on every page load. However you will have to be careful when you first initiate the $_SESSION variable to check whether it is already set. You dont want to over write the value everytime. So be sure to do:
每次加载页面时,输出计数都会增加 1。但是,当您第一次启动 $_SESSION 变量以检查它是否已经设置时,您必须小心。您不想每次都覆盖该值。所以一定要做到:
if (empty($_SESSION['SomeShop']))
$_SESSION['SomeShop'] = new Shop();
or better yet:
或者更好:
if (!$_SESSION['SomeShop'] instanceof Shop)
$_SESSION['SomeShop'] = new Shop();