从 PHP 中的 eval() 函数返回对会话变量的引用 [英] Returning a reference to a session variable from the eval() function in PHP

查看:64
本文介绍了从 PHP 中的 eval() 函数返回对会话变量的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你知道如何从 eval() 函数返回对 $_SESSION 变量的引用.

Do you know how to return a reference to a $_SESSION variable from the eval() function.

class SessionAccessor {
    static function &getVar() {
        return eval('return $_SESSION["sample"];');
    }
}

除了检查错误,这是我想要的结果:

Error checking aside, here is the result I want:

$sample =& SessionAccessor::getVar();
$sample = 'new value'; // sets $_SESSION['sample'] to 'new value'

如果您想知道我是否需要使用 eval(),答案是肯定的.

If you're wondering whether or not I need to use eval(), the answer is yes.

推荐答案

class SessionAccessor {
    static function &getVar($str) {
        $arr =& $_SESSION;
        foreach(explode('/',$str) as $path){
            $arr =& $arr[$path];
        }
        return $arr;
    }
}

您只需要遍历您想从数组中获取的路径并不断更新对它的引用.然后返回该引用.

You just need to loop over the path you want to get from the array and keep updating a reference to it. Then return that reference.

演示:http://codepad.org/mUS26ZAG

这篇关于从 PHP 中的 eval() 函数返回对会话变量的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆