【问题标题】:Logical operators should be avoided (use || instead of 'or') sensiolabs insight应避免使用逻辑运算符(使用 || 而不是“或”) sensiolabs insight
【发布时间】:2015-10-17 13:08:15
【问题描述】:

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

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

$handle = fopen($file, 'w') or die('Cannot open file: '.$file);

SensioLabs 说:

应避免使用逻辑运算符。

[...]

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

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

$handle = fopen($file, 'w') || die('Cannot open file: '.$file);

由于fopen 失败,我得到了经典的No such file or directory 错误, 而不是我所期望的(死亡动作和返回消息)。

为避免这种情况,我在执行fopen 之前使用了一个条件:

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

'||'有什么用在我想要的变量赋值中?

提前感谢您赐教。

【问题讨论】:

    标签: php logical-operators


    【解决方案1】:

    应避免使用逻辑运算符。

    在你的情况下是你想要的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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      相关资源
      最近更新 更多