PHP: setting session variables through variable variables
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
@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
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
Isn't this way better?
$key = 'element';
$_SESSION[$key] = 'value';
精彩评论