4
$_POST['asdf'] = 'something';

function test() {
    // NULL -- not what initially expected
    $string = '_POST';
    echo '====';
    var_dump(${$string});
    echo '====';

    // Works as expected
    echo '++++++';
    var_dump(${'_POST'});
    echo '++++++';

    // Works as expected
    global ${$string};
    var_dump(${$string});

}

// Works as expected
$string = '_POST';
var_dump(${$string});

test();

I am not getting why such behaviour.. can anybody explain.. i need to know why such behaviours. i am actually not getting the code..

3
  • 1
    What do you expect? If the actual behavior differs from your expectations, your expectations are wrong. Commented May 30, 2011 at 12:26
  • what do you think Oswald Commented May 30, 2011 at 12:28
  • like the first vardump inside function should work correctly.. and why third vardump inside function is working fine Commented May 30, 2011 at 12:28

2 Answers 2

10

Look at here

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.

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

5 Comments

can u explain me the third vardump inside test function
@Jaimin: This is because of global ${$string}; global declaration. If you comment out this line of code you will see the third var_dump also not working
Third var_dump() might work because global ${$string}} might create a local variable that refers to a global variable. I'm not sure that it really is what is technically being done when using global keyword, but that's my guess.
singh: by global ${$string}; this we are using superglobals and PHP says that "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." so how is it possilbe..
@Jaimin:You should Look at @mario 's answer he explained very well how it is working
4

PHP does not have real global variables. The "superglobals" are also a misnomer. $_POST and $_GET are never present in the local variable hash tables. They exist as aliases, which PHP only sees for ordinary accesses. The variable variable access method only ever looks into the current local hash table.

global $$string;
  //   $$string = & $GLOBALS[$string];

Is a nifty trick to create a reference to the superglobals in the local hash table. This is why after that statement, you are able to use variable variables to access the "superglobals".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.