我正在尝试在会话中存储对象
但是,当我执行以下操作时,我没有按预期获得输出
代码:
在会话中存储像这样的对象 -
$oEmployee = new Employee();
$_SESSION['Employee'] = $oEmployee;
我正试图像这样打印 -
print_r($_SESSION['Employee']);
echo "<br>";
$oEmployee = new $_SESSION['Employee'];
print_r($oEmployee);
这是我得到的输出:
Employee Object
(
[m_sFirstName:private] => Sac
[m_sLastName:private] => Kos
[m_sPhone:private] => 9876543210
[m_sEmail:private] => sac@kos.com
[m_sPassword:private] => password
[m_iEmployeeId:private] => 1
)
Employee Object
(
[m_sFirstName:private] =>
[m_sLastName:private] =>
[m_sPhone:private] =>
[m_sEmail:private] =>
[m_sPassword:private] =>
)
知道出了什么问题吗?
答案 0 :(得分:1)
问题在于您的行
$oEmployee = new $_SESSION['Employee'];
PHP将$_SESSION['Employee']
中的值转换为字符串,然后尝试实例化具有该名称的类(new
)。由于您没有向构造函数传递任何内容,因此实例化了一个空对象。
你在尝试在那条线上做什么?
答案 1 :(得分:0)
您应该在将对象写入会话之前对其进行序列化:
$oEmployee = new Employee();
$_SESSION['Employee'] = serialize($oEmployee);
之后你可以通过以下代码获得它:
$Employee = unserialize($_SESSION['Employee']);