I came across a bit of code working in someone else’s code for a form validator. It was supposed to return a value from the form data posted. Anyway, it was always returning NULL. This is what the function was in its entirety (the assumption is that this code did work at one point):
function _getValue($field)
{
global ${$field};
return ${$field};
}
From the context in the other functions, I could tell it was trying to get the value from the (in this case) $_POST variable. When I changed the function to the following, everything worked like a charm:
function _getValue($field)
{
// $_REQUEST should hold $_GET and $_POST values
return $_REQUEST[$field];
}
So my question is… what the heck is global ${$field} mean in this context? I know what ${$field} is, but let’s say they passed in email to that function. Where is this global $email variable coming from?
How is the original function supposed to have worked? I know there’s something called “Super Globals” or something and that’s bad. Is this related? Is that possibly why it stopped working? Did the host turn off Super Globals?
[EDIT] There was some obviously confusion in the way I phrased the question. I know what ${$field} and $$field means, but I don’t know how
global ${$field};
return ${$field};
returns the value the user put into a form like
<input name="email">
when you call
$this->_getValue('email');
The programmer before you expected the POST variables to be in the global space, because of the register_globals directive. Thankfully, this feature has been turned off by default in PHP 4.2 and removed in PHP 5.4.
To quote the documentation:
I wonder how could anyone think that was a good idea 🙂