包括/ session.php文件:
/*
Use the static method getInstance to get the object.
*/
class Session
{
const SESSION_STARTED = TRUE;
const SESSION_NOT_STARTED = FALSE;
// The state of the session
private $sessionState = self::SESSION_NOT_STARTED;
// THE only instance of the class
private static $instance;
protected function __construct() { }
public function __destruct() {
session_write_close();
}
/**
* Returns THE instance of 'Session'.
* The session is automatically initialized if it wasn't.
*
* @return object
**/
public static function GetInstance()
{
if ( !isset(self::$instance))
{
self::$instance = new self;
}
self::$instance->startSession();
return self::$instance;
}
public function getID() {
return session_id();
}
/**
* (Re)starts the session.
*
* @return bool TRUE if the session has been initialized, else FALSE.
**/
public function startSession()
{
if ( $this->sessionState == self::SESSION_NOT_STARTED )
{
$this->sessionState = session_start();
}
return $this->sessionState;
}
/**
* Creates a new session.
**/
public function newSession() {
return session_regenerate_id(true);
}
/**
* Stores datas in the session.
* Example: $instance->foo = 'bar';
*
* @param name Name of the datas.
* @param value Your datas.
* @return void
**/
public function __set( $name , $value )
{
$_SESSION[$name] = $value;
}
/**
* Gets datas from the session.
* Example: echo $instance->foo;
*
* @param name Name of the datas to get.
* @return mixed Datas stored in session.
**/
public function __get( $name )
{
if ( isset($_SESSION[$name]))
{
$ret = $_SESSION[$name];
return $ret;
}
}
public function __isset( $name )
{
return isset($_SESSION[$name]);
}
public function __unset( $name )
{
unset( $_SESSION[$name] );
}
/**
* Destroys the current session.
*
* @return bool TRUE is session has been deleted, else FALSE.
**/
public function destroy()
{
session_start();
session_unset();
session_destroy();
}
}
?>
test.php的:
<?php
require_once('include/session.php');
$session = Session::GetInstance();
$session->foo = 'bar';
$session->baz = array();
$session->baz['foo'] = 'bar';
$session->baz['derp'] = array();
$session->baz['derp']['php_sucks'] = 'this will never work';
var_dump($session->foo); echo '<br>';
var_dump($session->baz); echo '<br>';
var_dump($session->baz['foo']); echo '<br>';
var_dump($session->baz['derp']); echo '<br>';
var_dump($session->baz['derp']['php_sucks']); echo '<br>';
?>
输出:
string(3) "bar"
array(0) { }
NULL
NULL
NULL
为什么$ session-&gt; baz数组没有被填充?
答案 0 :(得分:2)
当您调用$ session-&gt; baz ['foo']时,$ session-&gt; baz会返回会话中数组的副本,然后向其中添加'foo'元素。此副本不是您班级内的副本,几乎立即被丢弃。
你需要改变处理数组的方式,即使用一些getter和setter(包括魔术数组),或者研究如何通过引用而不是复制来获取'baz'元素。