passes(string $attribute, $value) 声明:bool 必须与 Illuminate\Contracts\Validation\Rule::passes($attribute, $value) 兼容

Declaration of passes(string $attribute, $value): bool must be compatible with Illuminate\Contracts\Validation\Rule::passes($attribute, $value)

我已经创建了自定义验证规则

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Exception;

class ValidFoo implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes(string $attribute, $value): bool
    {
        if (!$foo) {
            return false;
        }

        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message(): string
    {
        return 'The foo you \'ve provided is not valid.';
    }
}

但是,当我尝试提交表单时出现此错误

Symfony\Component\Debug\Exception\FatalErrorException (E_UNKNOWN)
Declaration of App\Rules\ValidFoo::passes(string $attribute, $value): bool must be compatible with Illuminate\Contracts\Validation\Rule::passes($attribute, $value)

这是Laravel的规则界面

namespace Illuminate\Contracts\Validation;

interface Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value);

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message();
}
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Exception;

class ValidFoo implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if (!$foo) {
            return false;
        }

        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message(): string
    {
        return 'The foo you \'ve provided is not valid.';
    }
}

这是更正后的 class。发生错误是因为你使用了类型命中,但接口没有使用类型提示