PHP问号 [英] PHP question mark
问题描述
$hideCode = $likesObj->isAlreadyLikedByUser(facebookUID()) ? 'style="display:none;"' : '';
有人可以在这行代码中向我解释那个问号是做什么的吗?非常感谢!
Can anyone explain to me what that question mark does in this line of code? Thanks a lot!
推荐答案
这称为三元运算符,这是多种语言的通用语言,包括PHP,Javascript,Python,Ruby ...
This is called the Ternary Operator, and it's common to several languages, including PHP, Javascript, Python, Ruby...
$x = $condition ? $trueVal : $falseVal;
// same as:
if ($condition) {
$x = $trueVal;
} else {
$x = $falseVal;
}
在PHP中使用三进制时,需要注意的一个非常重要的一点是:
One very important point to note, when using a ternary in PHP is this:
注意:请注意,三元运算符是一个语句,它的结果不是变量,而是变量的结果.要知道是否要通过引用返回变量,这一点很重要.语句返回$ var == 42? $ a:$ b;因此,按引用返回功能中的无效将起作用,并且在更高版本的PHP中会发出警告. 源
Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions. source
这篇关于PHP问号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!