Possible Duplicate:
Class encapsulating $_SESSION – problem
include/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>';
?>
output:
string(3) "bar"
array(0) { }
NULL
NULL
NULL
Why isn’t the $session->baz array being filled?
When you call $session->baz[‘foo’], $session->baz returns a copy of the array that is in the session and then you add the ‘foo’ element to it. This copy is not the copy inside your class and is pretty much instantly discarded.
You’ll need to change the way you handle having arrays in there, ie using some getters and setters (including the magic ones) or look into ways of getting the ‘baz’ element out by reference instead of copy.