2

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?

12
  • Why would you access $_POST via variable variable names? What do you get when you do var_dump($$method)? Commented Apr 27, 2011 at 12:17
  • complete shot in the dark, but try ${$method}['password']. I'm wondering if the array is the problem and not the variable. Commented Apr 27, 2011 at 12:17
  • @Michael this allows you to decentralize the method you are using instead of using a bunch of conditionals. Commented Apr 27, 2011 at 12:18
  • Using the $$ syntax is bad news. It's not quite as bad a eval() but it's a pretty close second. Please try to avoid it -- there's always a better solution than this. Commented Apr 27, 2011 at 12:26
  • @Spudley what do you suggest? Commented Apr 27, 2011 at 12:30

3 Answers 3

5

From php manual:

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

Sign up to request clarification or add additional context in comments.

2 Comments

In his example $method is no longer a variable variable, it's a copy of the $_POST array and therefore no longer a super-global.
@Evert $method is indeed not a super-global, but Charles is still right, because in the end i do try to call the super-global $_POST through variable variables using $method.
3

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

Comments

1
$$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.

1 Comment

In my example, i would want ${$method}['password'] instead of ${$method['password']}, if wat Charles' answered wouldn't have been true.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.