PHP: setting session variables through variable variables

╄→гoц情女王★ 提交于 2020-01-04 06:04:14

问题


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

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

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?

Edit: 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


回答1:


@Mala, I think eval will help you. Check the code below. It may help you for what you want.

session_start();
    $_SESSION['user1'] = "User 1";
    $_SESSION['user2'] = "User 2";

    $key = "_SESSION['user3']";
    eval("\$$key = 'User 3';");

    foreach ($_SESSION as $key=>$value){
        echo $key." => ".$value."<br/>";
        unset($_SESSION[$key]);
    }
    session_destroy();

If you still have any trouble, Let me know. Thank you




回答2:


From PHP Documentation:

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.

EDIT

This little trick should give you what you want:

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

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




回答3:


Isn't this way better?

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


来源:https://stackoverflow.com/questions/7763720/php-setting-session-variables-through-variable-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!