How do I make PHP's Magic __set work like a natural variable?

Posted by Navarr on Stack Overflow See other posts from Stack Overflow or by Navarr
Published on 2010-05-15T05:01:02Z Indexed on 2010/05/15 5:14 UTC
Read the original article Hit count: 306

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about php

Related posts about magic-methods