简体   繁体   English

使用PHP 5.3?:运算符

[英]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; 这是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). 即使你使用了新的样式,你也会遇到问题?page=00评估为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. 表达式expr1?:expr3如果expr1的计算结果为TRUE则返回expr1,否则返回expr3。

So you'll still have to use isset or empty() - the ?: operator does not include an isset check. 所以你仍然需要使用isset或empty() - ?:运算符不包含isset检查。 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. 然而,许多人认为这是不可读的,尽管它比isset()结构短。

Or if you are using input objects or any other utility class: 或者,如果您正在使用输入对象或任何其他实用程序类:

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

It's because you're trying to typecast something that's undefined: (int) $_GET['page'] 这是因为你试图强调未定义的东西:(int)$ _GET ['page']

Remove the (int) or set the typecast after the conditional line. 删除(int)或在条件行之后设置类型转换。

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. 这是干净的,处理未定义的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM