Avoid duplicate code in statements like: isset($_GET['foo']['bar']) ? $_GET['foo']['bar'] : NULL;
To read unknown variables in PHP often I use code like the following:
$bar = isset($_GET['foo']['bar']) ? $_GET['foo']['bar'] : NULL;
I don't like to write the variable name twice. It just looks ugly and is too long for such an everyday task.
Do you know a better solution? Just using the @
operator or suppress notices at all is no option (bad practice, slow).
function ifset(&$value)
{
if(isset($value)) return $value;
}
$bar = ifset($_GET['foo']['bar']); // $_GET is empty
However this creates silently new unwanted variables with that name/path. A var_dump($_GET)
would print:
array(1) {
["foo"]开发者_如何转开发=>
array(1) {
["bar"]=>
NULL
}
}
Although this will not completely solve your problem, in some cases you can use extract($_GET);
<?php
/* Suppose that $var_array is an array returned from
wddx_deserialize */
$size = "large";
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape, $wddx_size\n";
?>
Use : "eval(foo,bar") see in a php manual for: eval.
Another way to redesign your function would be to make a recursive function that adds all of the set keys into an array as names and then simply check using in_array() function. If found, return value.
Finally PHP7 brings a solution. Yeah! The coalesce operator.
$bar = $_GET['foo']['bar'] ?? NULL;
If the value before the ??
exists and is not NULL
it returns that one, otherwise it takes the fallback value from behind the ??
. I love it!
精彩评论