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

问题描述

在 PHP 中,将完整对象存储为会话变量是否被认为是最佳实践?

In PHP, is it considered best practice to store the complete object as a session variable?

根据我的经验,有时有效,有时无效.有什么具体原因吗?

From my experience, sometimes it works and sometime not. Is there any specific reason for it?

示例:

session_start();
$object = new sample_object();
$_SESSION['sample'] = $object;

推荐答案

在 PHP 中使用 serialize() 之前存储您的对象,并在检索您的对象时调用 unserialize()来自会话的对象.

Use serialize() in PHP before store your object, and call unserialize() when retrieve your object from session.

存储对象

session_start();
$object = new sample_object();
$_SESSION['sample'] = serialize($object);

检索对象

session_start();
$object = unserialize($_SESSION['sample']);

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

08-26 03:09
查看更多