Session to object

<?php
//Usage Test
$my_session = new VrSession('my_session');

$my_session->test1 = 'value1'; //comment this line out to test 'unset' below
$my_session->test2 = 'value2';

//unset($my_session->test1);

echo '<pre>';
print_r($my_session);
echo '</pre>';

//Check for test 1
if(isset($my_session->test1)) echo '<br>test1 = ' . $my_session->test1 .'<br>';
else echo '<br>test1 not-set';

/* ~~~~~~~~~~ VrSession ~~~~~~~~~~ */

class VrSession{
private $namespace,$session = array();
public function __construct($namespace){
session_start();
$this->namespace = $namespace;
if($_SESSION[$this->namespace]) $this->session = $_SESSION[$this->namespace];
}
public function __set($name,$value){
$_SESSION[$this->namespace][$name] = $value;
$this->session[$name] = $value;
}
public function __get($name){
if(array_key_exists($name,$this->session)) return $this->session[$name];
else return false;
}
public function __isset($name){ return isset($this->session[$name]); }
public function __unset($name){
unset($_SESSION[$this->namespace][$name]);
unset($this->session[$name]);
}
}
?>

0 Comments

You must be logged in to post a comment.