$hideCode = $likesObj->isAlreadyLikedByUser(facebookUID()) ? 'style="display:none;"' : '';
任何人都可以向我解释一下这行代码中问号的作用吗?非常感谢!
最佳答案
这被称为 Ternary Operator ,并且它对多种语言都很常见,包括 PHP、Javascript、Python、Ruby...
$x = $condition ? $trueVal : $falseVal;
// same as:
if ($condition) {
$x = $trueVal;
} else {
$x = $falseVal;
}
在 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问号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6583673/