php - PhpStorm 中的 "Add #[Pure] attribute"检查是为了什么?

标签 php phpstorm php-8

我有一个非常简单的 FormRequest Laravel 项目中的类。两种方法,它们都返回一个由方法部分填充的简单数组,但 IDE 对它们的处理方式不同。

<?php

namespace App\Http\Requests;

class VerifyPhoneNumber extends FormRequest {
    use Support\ValidatesPhoneNumbers;

    public function authorize(): bool {
        return true;
    }

    public function rules(): array {
        return [
            "phone_number" => $this->getPhoneNumberRules(),
            "verify_code" => ["required", "numeric", "max:999999"],
        ];
    }

    public function messages(): array {
        return [
            "phone_number.regex" => $this->getPhoneNumberMessage(),
        ];
    }
}
以及非常基本的 trait 方法:
<?php

namespace App\Http\Requests\Support;

trait ValidatesPhoneNumbers {
    protected function getPhoneNumberMessage(): string {
        return __("Some localized error message");
    }

    protected function getPhoneNumberRules(): array {
        return ["regex:/^\+?1?[2-9][0-9]{5,14}$/", "max:16"];
    }
}
令我困惑的是IDE检查提示我应该添加JetBrains\PhpStorm\Pure归因于 rules()方法,但不是 messages()方法。
评论在 the class definition说:

The attribute marks the function that has no impact on the program state or passed parameters used after the function execution. This means that a function call that resolves to such a function can be safely removed if the execution result is not used in code afterwards.


这并没有真正给我任何线索,为什么它以不同的方式对待这两种方法。如果我正确理解第二句话,当“纯”方法的结果未使用时,IDE 会将方法的使用标记为未使用,并建议将其删除。
用于确定何时需要此属性的逻辑是什么?

最佳答案

如果一个函数只依赖于其他纯函数,那么它也是纯函数。自 getPhoneNumberRules()只返回一个固定数组,它是纯数组,所以 rules()也是纯的。
但是messages()电话getPhoneNumberMessage() ,它调用 __()如果位置状态改变,可以返回不同的本地化消息的函数,所以它不是纯的。

关于php - PhpStorm 中的 "Add #[Pure] attribute"检查是为了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69470268/

相关文章:

javascript - 刷新页面并调用同一个 anchor

php - 使用 mysql where in 语句时将文本值包装在字符串中

phpstorm - 如何防止 PhpStorm 在 ReflectionExceptions 上中断?

macos - PhpStorm 终端快捷键 : switch tab, 返回编辑器等(Mac)

php - 拉维Excel : how to get value of a cell?

phpstorm - 如果类在不同的命名空间中,则未定义类

php - 迁移到 PHP 8.0 : array_key_exists() improved performance. .. 不理解

php - 如何检测是否启用了 PHP JIT

php - 编译错误 : Cannot use positional argument after named argument

php - OsTicket + IIS + mySQL + 极慢的查询