3

I have a class for session handling that uses object overloading for __GET and __SET, I've been having issues with arrays and read to assign get by reference, such as &__GET

The problem is I can't update the values. For example, let's say I have this:

$session->item['one']['name']

I'd like to change it, by assigning it a new value; $session->item['one']['name'] = 'new value' However, it doesn't change.

Any ideas how to work around this? Below is the code, thank you!

class Session 
{

    private $_session = array();

    public function __construct()
    {

        if(!isset($_SESSION)) {
            session_start();
        }
        $this->_session = $_SESSION;
    }

    public function __isset($name)
    {
        return isset($this->_session[$name]);
    }

    public function __unset($name)
    {
        unset($_SESSION[$name]);
        unset($this->_session[$name]);
    } 

    public function &__get($name)
    {

        return $this->_session[$name];

    }

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

    public function getSession()
    {
        return (isset($this->_session)) ? $this->_session : false;
    }

    public function getSessionId()
    {
        return (isset($_SESSION)) ? session_id() : false;
    }


    public function destroy()
    {
        $_SESSION = array();
        session_destroy();
        session_write_close();
        unset($this->_session);
    }

}
2
  • 2
    Not posting this as an answer because I have no clue if it matters with $_SESSION, but have you tried doing $this->_session = &$_SESSION; in your constructor instead of how you're setting it now? Commented Dec 22, 2011 at 18:07
  • No I haven't and I just did and it freakin' works! Thank you! Please post as answer. Commented Dec 22, 2011 at 18:09

1 Answer 1

3

In your constructor, change $this->_session = $_SESSION; to $this->_session = &$_SESSION; so you're getting a reference to it inside of your class.

Sign up to request clarification or add additional context in comments.

1 Comment

If you finish the session, the reference still exists, however, it's not a reference to the (then current) superglobal any longer. So this is not compatible if you start a session, close it, and then start a second one in the same request. Implementing ArrayAccess can help here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.