lugte098
lugte098

Reputation: 2309

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?

Upvotes: 2

Views: 190

Answers (3)

mario
mario

Reputation: 145482

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();

Upvotes: 3

Charles Brunet
Charles Brunet

Reputation: 23110

From php manual:

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

Upvotes: 5

Evert
Evert

Reputation: 99515

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

is evaluated as:

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

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

Upvotes: 1

Related Questions