何时使用左括号和右括号以及何时不使用

when using open and close brackets and when not

我看到这段代码在 if/else 语句之前没有使用括号或 : 。我认为每条语句都应以 {: 开头 他们在这里不使用它的原因是什么?

if (!$this->Article)
        throw NotFoundException('Article');

    // Set required permission.
    $UserModel = new UserModel();
    if ($this->Article->Status != ArticleModel::STATUS_PUBLISHED)
        if (($this->Article->AttributionUserID == Gdn::Session()->UserID)
            && !$UserModel->CheckPermission($this->Article->AttributionUserID, 'Articles.Articles.Edit')
        )
            $this->Permission('Articles.Articles.View');
        else
            $this->Permission('Articles.Articles.Edit');
    else
        $this->Permission('Articles.Articles.View');

如果在 if 语句中有 2 个或更多运算符,请始终使用方括号。如果一个运营商,你可以跳过它们。

但我建议始终使用括号。

如果 if 语句 returns 为真时必须 运行 的代码只有一行,则不需要括号。 if 语句中需要括号,以防其中包含一行以上的代码。

如果 "if" 语句之间的代码由一行组成,您可以去掉括号“{”,但如果 "if" 语句的代码由多行组成,则必须使用它

您使用方括号向解释器指示 if 语句的开始和结束位置。但是,当 if 语句只有一行时,可以省略括号,解释器有条件地执行(或不执行)下一行。

这是否是一个好的做法值得商榷。

当只有一句要执行,或者只有一条控制语句时,可以避开括号...在这段代码中:

if (!$this->Article)
    throw NotFoundException('Article'); //Only one sentence


// Set required permission.
$UserModel = new UserModel();
if ($this->Article->Status != ArticleModel::STATUS_PUBLISHED)
    //Insde there is only one if/else
    if (($this->Article->AttributionUserID == Gdn::Session()->UserID)
        && !$UserModel->CheckPermission($this->Article->AttributionUserID, 'Articles.Articles.Edit')
    )
        //Inside there is only one sentence
        $this->Permission('Articles.Articles.View');
    else
        //Else statement contains only one sentence
        $this->Permission('Articles.Articles.Edit');
else
    //Else statement contains only one sentence
    $this->Permission('Articles.Articles.View');

第一个例子如果要执行2句,必须用括号括起来,像这样:

if (!$this->Article)
{
    $foo = true;
    throw NotFoundException('Article'); 
}

此致

请不要忘记使用 phpunit 计算代码覆盖率的边缘情况:

<?php
// Because it is "line based" and not statement base coverage
// one line will always have one coverage status
if (false) this_function_call_shows_up_as_covered();

// Due to how code coverage works internally these two lines are special.
// This line will show up as non executable
if (false)
    // This line will show up as covered because it is actually the 
    // coverage of the if statement in the line above that gets shown here!
    will_also_show_up_as_coveraged();

// To avoid this it is necessary that braces are used
if (false) {
    this_call_will_never_show_up_as_covered();
}
?>

有关详细信息,请参阅 https://phpunit.de/manual/current/en/code-coverage-analysis.html#code-coverage-analysis.edge-cases

在我看来,这是最好始终使用括号的原因之一,另一个原因是,调试您举的示例代码非常烦人。