开发者

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

开发者 https://www.devze.com 2022-12-30 14:39 出处:网络
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

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 functio开发者_开发技巧n __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".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号