PHP语法问题:问号和冒号是什么意思? [英] PHP syntax question: What does the question mark and colon mean?

查看:146
本文介绍了PHP语法问题:问号和冒号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
快速php语法问题

Possible Duplicate:
quick php syntax question

return $add_review ? FALSE : $arg;

问号和冒号是什么意思?

What do question mark and colon mean?

谢谢

推荐答案

这是PHP 三元运算符(也称为条件运算符)-如果第一个操作数的值为true,则作为第二个操作数的值,否则为第三个操作数.

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

将其视为可以在表达式中使用的"if"语句.在根据某些条件进行简洁的分配时可能非常有用,例如

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

还有一个简写版本(从PHP 5.3起).您可以省略中间操作数.如果为真,则运算符将作为第一个操作数,否则为第三个操作数.例如:

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

值得一提的是,上面的代码在使用$ _GET或$ _POST变量时会抛出未定义的索引通知,并且为了防止我们需要使用更长的版本,请使用isset

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

这篇关于PHP语法问题:问号和冒号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆