Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php variable variables problem

Tags:

php

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

like image 491
Jaimin Avatar asked Dec 10 '22 08:12

Jaimin


2 Answers

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.

like image 52
Shakti Singh Avatar answered Dec 11 '22 23:12

Shakti Singh


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".

like image 29
mario Avatar answered Dec 11 '22 21:12

mario