如何使用静态分析仪捕获PHP拼写错误?

发布于 2025-01-20 05:32:40 字数 404 浏览 4 评论 0原文

昨天我犯了一个错误,花了几个小时来修复它。我有这样的方法

{
    if (isset($data['y'])) {
        $this->y = $data['y'];
    }

    if (isset($data['z'])) {
        $this->y = $data['z']; // <- error here
    }
}

,是的,我分配 $this->y 两次,而不是一次 y 和一次 z :-(

所以问题:任何静态分析工具都可以捕获此类错误吗?我的 CI 工具链中有 PHP Storm 和 Rector、PHPStan、PHP CS Fixer,但他们错过了此错误。

I was made a mistake yesterday and spent hours to fix it. I have method like this

{
    if (isset($data['y'])) {
        $this->y = $data['y'];
    }

    if (isset($data['z'])) {
        $this->y = $data['z']; // <- error here
    }
}

And yes, I assign $this->y two times instead of one y and one z :-(

So question: can any static analyze tools catch such errors? I have PHP Storm and Rector, PHPStan, PHP CS Fixer in my CI toolchain but they missed this error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

错々过的事 2025-01-27 05:32:40

这并不是一个答案,但它太复杂了,无法发表评论。

正如评论所指出的,机器人根本无法弄清楚你写的不是你想要的。最简单的解决方案是忍受人性的弱点并调试代码。

但这并不意味着您无法编写代码来更好地表达您的意图。考虑一下:

{
    $fields = ['x', 'y'];

    foreach ($fields as $field) {
        if (isset($data[$field]) {
            $this->$field = $data[$field];
        }
    }
}

现在您已经在代码中表达了您只想分配类似名称的字段。

This isn't so much an answer, but it's too complicated to put in a comment.

As the comments pointed out, there's simply no way for a robot to figure out that what you wrote isn't what you intended. The easiest solution is to live with human frailty and debug your code.

But that doesn't mean you can't write your code to better express your intent. Consider:

{
    $fields = ['x', 'y'];

    foreach ($fields as $field) {
        if (isset($data[$field]) {
            $this->$field = $data[$field];
        }
    }
}

Now you have expressed in you code that you only want to assign like-named fields.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文