什么是 ?: 在 PHP 5.3 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2153180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is ?: in PHP 5.3?
提问by JasonDavis
Possible Duplicate:What are the PHP operators “?” and “:” called and what do they do?
From http://twitto.org/
<?PHP
require __DIR__.'/c.php';
if (!is_callable($c = @$_GET['c'] ?: function() { echo 'Woah!'; }))
throw new Exception('Error');
$c();
?>
Twitto uses several new features available as of PHP 5.3:
从 PHP 5.3 开始,Twitto 使用了几个可用的新功能:
- The DIRconstant
- The ?: operator
- Anonymous functions
- 将DIR不变
- 运营商
- 匿名函数
What does number 2 do with the ?:in PHP 5.3?
Also, what do they mean by anonymous functions? Wasn't that something that has existed for a while?
数字 2 与?:在 PHP 5.3 中有什么关系?
另外,匿名函数是什么意思?那不是已经存在了一段时间的东西吗?
回答by Ben James
?:is a form of the conditional operator which was previously available only as:
?:是条件运算符的一种形式,以前只能用作:
expr ? val_if_true : val_if_false
In 5.3 it's possible to leave out the middle part, e.g. expr ?: val_if_falsewhich is equivalent to:
在 5.3 中可以省略中间部分,例如expr ?: val_if_false相当于:
expr ? expr : val_if_false
From the manual:
从手册:
Since PHP 5.3, it is possible to leave out the middle part of the conditional operator. Expression
expr1 ?: expr3returnsexpr1ifexpr1evaluates toTRUE, andexpr3otherwise.
自 PHP 5.3 起,可以省略条件运算符的中间部分。如果计算结果为,则表达式
expr1 ?: expr3返回,否则返回。expr1expr1TRUEexpr3
回答by Gumbo
The ?:operator is the conditional operator(often refered to as the ternary operator):
该?:操作员是有条件的操作者(通常refered为三元运算符):
The expression
(expr1) ? (expr2) : (expr3)evaluates toexpr2ifexpr1evaluates to TRUE, andexpr3ifexpr1evaluates to FALSE.
表达式
(expr1) ? (expr2) : (expr3)计算为expr2ifexpr1计算为TRUE,expr3ifexpr1计算为FALSE。
In the case of:
如果是:
expr1 ?: expr2
The expression evaluates to the value of expr1if expr1is trueand expr2otherwise:
该表达式的值expr1如果expr1是真和expr2否则:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3returnsexpr1ifexpr1evaluates to TRUE, andexpr3otherwise.
自 PHP 5.3 起,可以省略三元运算符的中间部分。如果计算结果为TRUE,则表达式
expr1 ?: expr3返回,否则返回。expr1expr1expr3
回答by Boldewyn
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
自 PHP 5.3 起,可以省略三元运算符的中间部分。表达式 expr1 ?: 如果 expr1 的计算结果为 TRUE,则 expr3 返回 expr1,否则返回 expr3。
Anonymous functions:No, they didn't exist before 5.3.0(see the first note below the examples), at least in this way:
匿名函数:不,它们在 5.3.0 之前不存在(请参阅示例下方的第一个注释),至少以这种方式:
function ($arg) { /* func body */ }
The only way was create_function(), which is slower, quite cumbersome and error prone (because of using strings for function definitions).
唯一的方法是create_function(),它更慢,相当麻烦且容易出错(因为使用字符串来定义函数)。

