Skip to content

Instantly share code, notes, and snippets.

@astorm
Created August 3, 2015 22:28
Show Gist options
  • Save astorm/f7f75f75604cc20e2116 to your computer and use it in GitHub Desktop.
Save astorm/f7f75f75604cc20e2116 to your computer and use it in GitHub Desktop.
Answer to: http://stackoverflow.com/questions/31797607/undefined-variable-get, obnoxious closed because it wasn't in english.

Apologies for the English, but I don't speak or read your language (Russian?). This answer is based on Google translate's version of what you asked.

PHP's super globals ($_GET, $_POST, etc.) are special variables, and it looks like you can't use these variables with PHP's variable variable feature. For example, this works

$foo = ['Hello'];    
$var_name = 'foo';
var_dump($$var_name);

The "variable variable" $$var_name expands as $'foo'/$foo, and the variable dumps correctly.

However, the following does not work

$var_name = '_GET';
var_dump($$var_name);

It appears that whatever magic scope variable variables live in, that scope doesn't include the super globals. You'll need to rethink your approach. One way you might do this is by accepting the actual array instead of a string that's it's name, and specifying a "by reference" parameter in your function to avoid any performance issues

function _getArray(&$array, $key)
{
    if(!is_array($array)) { throw new Exception("Invalid argumnet!");}
    if(array_key_exists($key, $array))
    {
        return $array[$key];
    }

    return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment