应避免使用逻辑运算符(使用 || 而不是 'or') sensiolabs insight
Logical operators should be avoided (use || instead of 'or') sensiolabs insight
我使用 SensioLabs Insight 使我的项目代码质量保持在所用工具的最佳实践之上。
此行在 SLInsight 分析期间引起警告:
$handle = fopen($file, 'w') or die('Cannot open file: '.$file);
SensioLabs 说:
Logical operators should be avoided.
[...]
The or operator does not have the same precedence as ||. This could lead to unexpected behavior, use || instead.
好的,但是,如果我只是使用 ||而不是 'or' ,像这样:
$handle = fopen($file, 'w') || die('Cannot open file: '.$file);
我得到了经典的 No such file or directory
错误,因为 fopen
失败了,
而不是我所期待的(死动作和 return 消息)。
为了避免这种情况,我在 fopen
:
之前使用了一个条件
if(!file_exists($file)) {
throw $this->createNotFoundException('Le fichier '.$file.' n\'existe pas.');
}
$handle = fopen($file'.log', 'r');
'||'有什么用在我想要的变量赋值中?
谢谢你的启发。
Logical operators should be avoided.
在您的情况下,您想要的 or
具有优先级。我认为 SensioLabs 指的是条件中的复杂表达式,这可能会产生误导。
or
运算符的优先级较低,甚至低于赋值 =
运算符。示例:
if ($a = getRecordOrFalse($userId) || $boolValue) {
如您所料:
if (($a = getRecordOrFalse($userId)) || ($boolValue)) {
$a
包含返回的值 getRecordOrFalse
,如果 $boolValue
为真,则此条件为 true
,即使 $a
不是。但是使用 or
你会得到完全不同的行为:
if ($a = getRecordOrFalse($userId) or $boolValue) {
相当于:
if ($a = (getRecordOrFalse($userId) or $boolValue)) {
现在 $a
将是 getRecordOrFalse($userId) or $boolValue)
条件的结果给出的布尔值。
但在你的情况下这是有道理的:
$handle = (fopen($file, 'w') or die('Cannot open file: '.$file));
提高可读性的方法是使用如下条件:
if (false === $handle = fopen($file, 'w')) {
die('Cannot open file: '.$file);
}
或者干脆
if (!$handle = fopen($file, 'w')) {
die('Cannot open file: '.$file);
}
我使用 SensioLabs Insight 使我的项目代码质量保持在所用工具的最佳实践之上。
此行在 SLInsight 分析期间引起警告:
$handle = fopen($file, 'w') or die('Cannot open file: '.$file);
SensioLabs 说:
Logical operators should be avoided.
[...]
The or operator does not have the same precedence as ||. This could lead to unexpected behavior, use || instead.
好的,但是,如果我只是使用 ||而不是 'or' ,像这样:
$handle = fopen($file, 'w') || die('Cannot open file: '.$file);
我得到了经典的 No such file or directory
错误,因为 fopen
失败了,
而不是我所期待的(死动作和 return 消息)。
为了避免这种情况,我在 fopen
:
if(!file_exists($file)) {
throw $this->createNotFoundException('Le fichier '.$file.' n\'existe pas.');
}
$handle = fopen($file'.log', 'r');
'||'有什么用在我想要的变量赋值中?
谢谢你的启发。
Logical operators should be avoided.
在您的情况下,您想要的 or
具有优先级。我认为 SensioLabs 指的是条件中的复杂表达式,这可能会产生误导。
or
运算符的优先级较低,甚至低于赋值 =
运算符。示例:
if ($a = getRecordOrFalse($userId) || $boolValue) {
如您所料:
if (($a = getRecordOrFalse($userId)) || ($boolValue)) {
$a
包含返回的值 getRecordOrFalse
,如果 $boolValue
为真,则此条件为 true
,即使 $a
不是。但是使用 or
你会得到完全不同的行为:
if ($a = getRecordOrFalse($userId) or $boolValue) {
相当于:
if ($a = (getRecordOrFalse($userId) or $boolValue)) {
现在 $a
将是 getRecordOrFalse($userId) or $boolValue)
条件的结果给出的布尔值。
但在你的情况下这是有道理的:
$handle = (fopen($file, 'w') or die('Cannot open file: '.$file));
提高可读性的方法是使用如下条件:
if (false === $handle = fopen($file, 'w')) {
die('Cannot open file: '.$file);
}
或者干脆
if (!$handle = fopen($file, 'w')) {
die('Cannot open file: '.$file);
}