views:

178

answers:

1

Basically, what I want to do is create a class called Variables that uses sessions to store everything in it, allowing me to quickly get and store data that needs to be used throughout the entire site without working directly with sessions.

Right now, my code looks like this:

<?php
    class Variables
    {
            public function __construct()
            {
                    if(session_id() === "")
                    {
                            session_start();
                    }
            }
            public function __set($name,$value)
            {
                    $_SESSION["Variables"][$name] = $value;
            }
            public function __get($name)
            {
                    return $_SESSION["Variables"][$name];
            }
            public function __isset($name)
            {
                    return isset($_SESSION["Variables"][$name]);
            }
    }

However, when I try to use it like a natural variable, for example...

$tpl = new Variables;
$tpl->test[2] = Moo;
echo($tpl->test[2]);

I end up getting "o" instead of "Moo" as it sets test to be "Moo," completely ignoring the array. I know I can work around it by doing

$tpl->test = array("Test","Test","Moo");
echo($tpl->test[2]);

but I would like to be able to use it as if it was a natural variable. Is this possible?

+2  A: 

You'll want to make __get return by reference:

<?php
class Variables
{
        public function __construct()
        {
                if(session_id() === "")
                {
                        session_start();
                }
        }
        public function __set($name,$value)
        {
                $_SESSION["Variables"][$name] = $value;
        }
        public function &__get($name)
        {
                return $_SESSION["Variables"][$name];
        }
        public function __isset($name)
        {
                return isset($_SESSION["Variables"][$name]);
        }
}

$tpl = new Variables;
$tpl->test[2] = "Moo";
echo($tpl->test[2]);

Gives "Moo".

Artefacto
I didnt think you could overload __get/set with the by reference operator...
prodigitalson
In fact, you must overload __get. Otherwise you receive a message Indirect modification of overloaded property Variables::$test has no effect. When you use $tpl->test[2] = "Moo"; the actual handler that is being called is not __set; it's __get. You are not saying "store in $tpl->test the array(2=>"Moo")", you are saying "modify the $tpl->test array so that it's 2 key maps to the value "Moo"". For that, you need to call __get and __get needs to return by reference. You may think this could be done with a pair of __get/__set, but why it's not possible does not fit in this comment.
Artefacto