IMS*_*SoP 14
PSR-2标准明确忽略了对运营商的任何意见:
本指南有意省略了许多风格和实践元素.这些包括但不限于:......运营商和任务
由于括号用于对表达式进行分组,因此您的示例没有多大意义:
$error = ($error_status) ? 'Error' : 'No Error';
Run Code Online (Sandbox Code Playgroud)
这里围绕括号中的单个变量没有任何意义.更复杂的情况可能会从括号中受益,但在大多数情况下,它们只是为了可读性.
更常见的模式是始终围绕整个三元表达式:
$error = ($error_status ? 'Error' : 'No Error');
Run Code Online (Sandbox Code Playgroud)
这样做的主要动机是PHP中的三元运算符具有相当笨拙的关联性和优先级,因此在复杂表达式中使用它通常会产生意外/无用的结果.
常见的情况是字符串连接,例如:
$error = 'Status: ' . $error_status ? 'Error' : 'No Error';
Run Code Online (Sandbox Code Playgroud)
这里连接(.运算符)实际上是在三元运算符之前求值的,因此条件总是非空字符串(开始'Status: '),并且总是得到字符串Error'作为结果.
括号是防止这种情况的必要条件:
$error = 'Status: ' . ($error_status ? 'Error' : 'No Error');
Run Code Online (Sandbox Code Playgroud)
当"堆叠"三元表达式形成if-elseif链的等价时,存在类似的情况,因为PHP历史早期的错误意味着从左到右依次评估多个三元运算符,而不是在条件时快捷整个假分支是真的.
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5533 次 |
| 最近记录: |