Using PHP 5.3 ?: operator
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"?
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.
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;
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);
链接地址: http://www.djcxy.com/p/1738.html
上一篇: PHP中C#的空合并运算符(??)
下一篇: 使用PHP 5.3?:运算符