PSR-2 标准 https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md特别省略对运营商的任何意见:
本指南有意省略了许多风格和实践元素。这些包括但不限于:
... 运算符和赋值
由于括号用于对表达式进行分组,因此您的示例没有多大意义:
$error = ($error_status) ? 'Error' : 'No Error';
这里将单个变量括在括号中是没有意义的。更复杂的条件可能会受益于括号,但在大多数情况下,它们只是为了可读性。
更常见的模式是始终包围整个三元表达式:
$error = ($error_status ? 'Error' : 'No Error');
这样做的主要动机是 PHP 中的三元运算符具有相当尴尬的关联性和优先级,因此在复杂表达式中使用它通常会产生意外/无用的结果。
常见的情况是字符串连接,例如:
$error = 'Status: ' . $error_status ? 'Error' : 'No Error';
这里的串联(.
运算符)实际上被评估before三元运算符,因此条件始终是非空字符串(开头'Status: '
),你总是会得到字符串Error'
作为结果。
需要使用括号来防止这种情况发生:
$error = 'Status: ' . ($error_status ? 'Error' : 'No Error');
当“堆叠”三元表达式以形成 if-elseif 链的等价物时,也存在类似的情况,因为 PHP 历史早期的一个错误意味着多个三元运算符按从左到右的顺序计算,而不是在满足条件时捷径整个错误分支是真的。
一个例子来自PHP 手册 http://php.net/manual/en/language.operators.comparison.php更清楚地解释了这一点:
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.