Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting array values in $_SESSION through an accessor method

Can anyone please explain to me why the following code does not set the values on the array as expected? $_SESSION['foo'] stays empty, even after assigning time() and rand(). I've checked, the __get accessor method is actually called when assigning the variables but they aren't stored for one reason or another.

$test = Session::getSession('test');
$test->foo = array();
$test->foo[] = time();
$test->foo['baz'] = rand(1,9);
var_dump($_SESSION);

Using this simple Session wrapper

class Session 
{

    protected $namespace = null;

    public static function getSession($namespace) 
    {
        return new Session($namespace);
    }

    public static function destroySession($namespace) 
    {
        if(isset($_SESSION[$namespace])) {
            unset($_SESSION[$namespace]);
            return true;
        }

        return false;
    }

    private function __construct($namespace) 
    {
        $this->namespace = $namespace;

        if(!isset($_SESSION[$namespace])) {
            $_SESSION[$namespace] = null;
        }
    }

    public function &__get($name)
    {
        return (isset($_SESSION[$this->namespace][$name])) ? $_SESSION[$this->namespace][$name] : null;
    }

    public function __set($name, $value)
    {
        $_SESSION[$this->namespace][$name] = $value;
    }

}

In case it might be relevant, i'm using php 5.3.6

like image 862
ChrisR Avatar asked Feb 20 '26 08:02

ChrisR


1 Answers

I 'm not sure if this can be made to work at all.

For one, to return by reference you should add the & operator at the call site as well. I 'm not sure how that might be possible without screwing up the nice syntax you 're trying to achieve.

Also, you cannot return expressions by reference (only variables). So this won't work:

public function &__get($name)
{
    return (isset($_SESSION[$this->namespace][$name])) 
        ? $_SESSION[$this->namespace][$name] 
        : null;
}

At the very least it should be written as

public function &__get($name)
{
    $value = isset($_SESSION[$this->namespace][$name])
             ? $_SESSION[$this->namespace][$name]
             : null;
    return $value;
}
like image 143
Jon Avatar answered Feb 22 '26 21:02

Jon