简体   繁体   中英

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

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?

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM