PHP:通过变量变量设置会话变量 [英] PHP: setting session variables through variable variables

查看:125
本文介绍了PHP:通过变量变量设置会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个类似于以下内容的会话变量:

I would like to set a session variable with something akin to:

$key = '_SESSION[element]';
$$key = 'value';

这确实将$_SESSION['element']设置为与value相等,但是它似乎也清除了我的$_SESSION变量的其余部分,导致$_SESSION数组仅包含新的键/值对.

This does indeed set $_SESSION['element'] equal to value, but it also seems to clear the rest of my $_SESSION variable, resulting in the $_SESSION array only containing the new key/value pair.

我如何使用可变变量而不是对其进行操作来写入会话?

How can I write into the session using variable variables without nuking it?

编辑:如果无法做到这一点,那么,我们可能必须重组并以正确"的方式进行操作.我只是想知道是否有简单的解决方法

if this can't be done, so be it, we'll probably have to restructure and do things the "right" way. I just wanted to know if there was an easy fix

推荐答案

来自 PHP文档:

请注意,变量变量不能与PHP一起使用 函数或类方法中的超全局数组.变量 $ this也是无法引用的特殊变量 动态地

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

您如何最终遇到这样的情况,确实令人怀疑.您可能做错了事.

How you ended up with a situation like this, is really questionable. You're probably doing something wrong.

编辑

这个小把戏应该给你你想要的东西:

This little trick should give you what you want:

$key = '_SESSION[element]';
$key = str_replace(array('_SESSION[', ']'), '', $key);
$_SESSION[$key] = 'value';
var_dump($_SESSION);

这基本上会产生与xdazz答案相同的结果

This will basically produce the same results as xdazz's answer

这篇关于PHP:通过变量变量设置会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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