开发者

An unnset-variable default value?

alot of time in programming the value of variables are passed through url parameters, in php;

if (isset($_GET['var'])) 开发者_如何学Go{$var = $_GET['var'];}

But if that does not execute, we will have an unset variable, in which may cause errors in the remaining of the code, i usually set the variable to '' or false;

else {$var = '';}

I was wondering what are the best practices, and why : )

thank you!


create a function

function get($name, $default = "") {
   return isset($_GET[$name]) ? $_GET[$name] : $default;
}


I favour using the ?: ternary operator

$var = isset($_GET['var'])) ? $_GET['var'] : 0;

but you can often combine this with code to sanitize your inputs too, e.g. if you're expecting a purely numeric argument:

$var = isset($_GET['var'])) ? intval($_GET['var']) : 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜