【问题标题】:Explicit variable declaration when using extract()使用 extract() 时的显式变量声明
【发布时间】:2016-12-04 12:23:55
【问题描述】:

我有以下sn-p:

protected function sendEmail($email)
{
    extract($email);

    $this->transmail->locale($locale)
                    ->timezone($timezone)
                    ->template($template)
                    ->subject($subject)
                    ->send($header, $params);
}

此代码完美运行 (full source code here)。但是,我想确保在旅途中遵循一些好的做法。我现在收到 [一些 CodeClimate 警告] (PHPMD)(https://codeclimate.com/github/timegridio/timegrid/app/Listeners/SendBookingNotification.php):

  • 避免使用未使用的局部变量,例如“$locale”。
  • 避免使用未使用的局部变量,例如“$timezone”。
  • 避免使用未使用的局部变量,例如“$template”。
  • 避免使用未使用的局部变量,例如“$subject”。
  • 避免使用未使用的局部变量,例如“$header”。
  • 避免使用未使用的局部变量,例如“$params”。

有哪些优雅的方式来解决它?

我应该用list() 或类似的东西显式声明变量吗?

提前致谢

【问题讨论】:

  • 如果您正在使用 PHPStorm,只需将其设置为从 PHPMD 中排除此文件(或方法)...没有什么是完美的。它将在顶部附加特殊的 phpdocblock,因此没有其他开发人员有相同的警告。
  • 谢谢,@Kyslik。那么这个 phpdocblock 是由 phpmd 解释的吗?在这种情况下,它看起来很公平,因为无论如何您都明确了代码意图(变量声明)。
  • 只需在 $this->transmail 上方使用这个/** @noinspection PhpUndefinedVariableInspection */,检测器就会忽略它(或者更好地说:phpstorm 将不允许在下一条语句上运行检查)
  • @Kyslik 谢谢,我会尝试并回复
  • 等一下,看看这个列表,gist.github.com/discordier/ed4b9cba14652e7212f5 我现在正在测试它,但似乎 phpmd 仍然报告问题。

标签: php laravel laravel-5 phpmd code-climate


【解决方案1】:

您可以使用 doc 注释注释从 PHPMD 中排除方法或类,或禁止某些软件工件的特殊规则。

/**
 * This will suppress all the PMD warnings in
 * this class.
 *
 * @SuppressWarnings(PHPMD)
 */
class Bar {
    function  foo() {
        $baz = 23;
    }
}

或者您可以使用这样的注释来禁止一条规则:

/**
 *
 */
class Bar {
    /**
     * This will suppress UnusedLocalVariable
     * warnings in this method
     *
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */
    public function foo() {
        $baz = 42;
    }
}

来源https://phpmd.org/documentation/suppress-warnings.html


不使用 PHPMD 的 PHPStorm 用户可以使用

/** @noinspection RULE */

规则可以在这里找到

https://gist.github.com/discordier/ed4b9cba14652e7212f5

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 2014-03-06
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多