简体   繁体   中英

php $_POST using $$ call

I'm aware that the following piece of code is possible in php:

$dog = 'Woof!';
$cat = 'Miauw!';
$animal = 'dog';
var_dump($$animal);

Output: 'Woof!'

Of course this is a simplified example of my actual code, nonetheless you get the idea. Now I can't seem to get the $_POST variable to act the same way.

Example:

$method = '_POST';
$$method['password'] = array();
// In the end i would want this piece of code above to do what i typed below
$_POST['password'] = array();

Output: 'Notice: Undefined variable: _POST'

So does this mean it is not possible to call $_POST this way or am I doing it the wrong way?

From php manual :

Note: Variable variables Superglobals cannot be used as variable variables inside functions or class methods.

As outlined by the other answers, not even the superglobals are real globals in PHP. They need to be specifically imported into the local scope dict to be accessible with variable variables.

If you really only want to access $_POST and $_GET or $_REQUEST, then the explicit syntax would be however:

$GLOBALS[$method]['password'] = array();
$$method['password'] = array();

is evaluated as:

${$method['password']} = array();

PS: You might be better off not doing this. Variable variables are confusing and considered a bit of a bad practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM