应该避免使用逻辑运算符(使用||而不是'或')sensiolabs洞察力

cha*_*asr 2 php logical-operators

我正在使用SensioLabs Insight将我的项目代码质量保持在使用过的工具的最佳实践之上.

此行在SLInsight分析期间导致警告:

$handle = fopen($file, 'w') or die('Cannot open file: '.$file);
Run Code Online (Sandbox Code Playgroud)

SensioLabs说:

应避免使用逻辑运算符.

[...]

or运算符与||的优先级不同.这可能导致意外行为,使用|| 代替.

好的,但是,如果我只是使用|| 而不是'或',像这样:

$handle = fopen($file, 'w') || die('Cannot open file: '.$file);
Run Code Online (Sandbox Code Playgroud)

No such file or directory因为fopen失败而得到了经典的错误,而不是我所期待的(死亡动作和回复消息).

为避免这种情况,我在使用条件之前执行以下操作fopen:

if(!file_exists($file)) {
    throw $this->createNotFoundException('Le fichier '.$file.' n\'existe pas.');
}
$handle = fopen($file'.log', 'r');
Run Code Online (Sandbox Code Playgroud)

什么是'||'的好用 在我想要的变量任务?

感谢先生,赐教.

Fed*_*kun 5

应避免使用逻辑运算符.

在你的情况下是or你想要的优先级.我认为SensioLabs指的是条件中的复杂表达,这可能会产生误导.

or运算符具有较低的优先级,甚至低于赋值=运算符.例:

if ($a = getRecordOrFalse($userId) || $boolValue) {
Run Code Online (Sandbox Code Playgroud)

如你所料:

if (($a = getRecordOrFalse($userId)) || ($boolValue)) {
Run Code Online (Sandbox Code Playgroud)

$a包含返回的值getRecordOrFalse,true如果$boolValue为true,则此条件为true,即使$a不是.但随着or你得到一个完全不同的行为:

if ($a = getRecordOrFalse($userId) or $boolValue) {
Run Code Online (Sandbox Code Playgroud)

这相当于:

if ($a = (getRecordOrFalse($userId) or $boolValue)) {
Run Code Online (Sandbox Code Playgroud)

现在$a将是getRecordOrFalse($userId) or $boolValue)条件结果给出的布尔值.

但在你的情况下这是有道理的:

$handle = (fopen($file, 'w') or die('Cannot open file: '.$file));
Run Code Online (Sandbox Code Playgroud)

你可以做些什么来提高可读性是使用这样的条件:

if (false === $handle = fopen($file, 'w')) {
    die('Cannot open file: '.$file);
}
Run Code Online (Sandbox Code Playgroud)

或者干脆

if (!$handle = fopen($file, 'w')) {
    die('Cannot open file: '.$file);
}
Run Code Online (Sandbox Code Playgroud)