PHP: setting session variables through variable va

2019-07-21 11:33发布

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

3条回答
Melony?
2楼-- · 2019-07-21 11:49

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楼-- · 2019-07-21 11:49

Isn't this way better?

$key = 'element';
$_SESSION[$key] = 'value';
查看更多
再贱就再见
4楼-- · 2019-07-21 12:13

@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

查看更多
登录 后发表回答