I am working on a function that takes a string as an argument, which I need to use to get the value of a variable of the same name.
For example
If the string $foo = "$_POST['email']";
is passed I need to retrieve the value of $_POST['email']
and store it as $example
, so that $_POST['email'] == $example
would return true. There is no feasable way of passing the value directly to function (the variable has to be dynamic to m开发者_运维问答ake the function worthwhile).
I did think of using variable variables but they don't work with super globals which will be the primary source of the values I need.
Basically is there a way to get the value of a variable (usually in a superglobal array) with the needed variable as a string?
Let me know if more detail is needed.
Thanks
Variable variables would be the answer, but if you're after fetching values from $_POST
array, why not pass just a key to a function?
Note: ths function is provided just for example, my actual recommendation is below.
function fetchFromPost($key) {
if(isset($_POST[$key]) {
return $_POST[$key];
} else {
return null; //or do whatever you want to do in case key is not found
}
}
In fact filter_input(), which allows you to chose an input array, a key and a sanitaion filter to be used, is already there for you
It is possible, although I seriously doubt you should use this. It allows for PHP injection and makes your source code very vulnerable if you don't know where the string came from:
<?
function eval_expression($expression)
{
eval("\$temp = $expression;");
return $temp;
}
// Usage:
echo eval_expression("\$_GET['plop']");
精彩评论