Using PHP 5.3 ?: operator

别来无恙 提交于 2019-12-10 14:16:23

问题


With this test page:

$page   = (int) $_GET['page'] ?: '1';
echo $page;

I don't understand the output I'm getting when page is undefined:

Request   Result
?page=2   2
?page=3   3
?page=    1
?         error: Undefined index page

Why the error message? It's PHP 5.3; why doesn't it echo "1"?


回答1:


The proper way (in my opinion) would be:

$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;

Even if you used the new style, you would have problems with ?page=0 (as 0 evaluated to false). "New" is not always better... you have to know when to use it.




回答2:


Unfortunately you cannot use it for the purpose you'd like to use it for:

Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

So you'll still have to use isset or empty() - the ?: operator does not include an isset check. What you need to use is:

$page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;



回答3:


Just for completeness, another way to achieve it is to pull operator rank:

 $page = (int)$_GET["page"]  or  $page = 1;

Many people perceive this as unreadable however, though it's shorter than isset() constructs.

Or if you are using input objects or any other utility class:

 $page = $_GET->int->default("page", 1);



回答4:


It's because you're trying to typecast something that's undefined: (int) $_GET['page']

Remove the (int) or set the typecast after the conditional line.




回答5:


If bloat is your concern, how about a helper function?

function get_or($index, $default) {
    return isset($_GET[$index]) ? $_GET[$index] : $default;
}

then you can just use:

$page = get_or('page', 1);

which is clean and handles undefined values.



来源:https://stackoverflow.com/questions/4210187/using-php-5-3-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!