Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP overloading return by reference, update value in array

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);
    }

}
like image 993
David Avatar asked Mar 20 '26 18:03

David


1 Answers

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

like image 173
jprofitt Avatar answered Mar 22 '26 07:03

jprofitt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!