【问题标题】:Laravel/PHP: is there a limit on number of arguments passed to closure functionLaravel/PHP:传递给闭包函数的参数数量是否有限制
【发布时间】:2021-12-04 00:15:27
【问题描述】:

当我试图覆盖默认密码重置功能时,我遇到了一些奇怪的关闭问题。

        $response = $this->broker()->reset(
            // the 3rd variable $pwAge has to be passed via use()
            $this->credentials($request), function ($user, $password) use($pwAge) {
                $this->resetPassword($user, $password, $pwAge);
            }
        );

第三个变量 $pwAge 必须通过

传递给闭包
use($pwAge)

如果与前两个参数一起传递:

        $response = $this->broker()->reset(
            $this->credentials($request), function ($user, $password, $pwAge) {
                $this->resetPassword($user, $password, $pwAge);
            }
        );

调用这个函数会报如下错误:

Symfony\Component\Debug\Exception\FatalThrowableError
Too few arguments to function App\Http\Controllers\Auth\ResetPasswordController::App\Http\Controllers\Auth\{closure}(), 2 passed in vendor\laravel\framework\src\Illuminate\Auth\Passwords\PasswordBroker.php on line 96 and exactly 3 expected 

我在这里缺少什么?请指教,谢谢。

【问题讨论】:

    标签: php laravel closures


    【解决方案1】:

    闭包中的参数数量限制为在调用函数时提供的参数数量。

    调用该函数的任何东西(在这种情况下为PasswordBroker.php)都会提供$user$password;它不知道$pwAge 变量,当然也不知道应该将它传递给函数。

    您可以通过使用 use ($pwAge) 将其添加到闭包范围内来使用该变量。

    考虑以下伪代码示例:

    function doSomething($cb) {
      $result = doSomeStuff();
      cb($result);
    }
    
    doSomething(function ($result) {
      doSomethingElse($result);
    });
    

    对我来说,实际上看到闭包在其他地方被调用有助于我理解我无法控制传递给闭包的参数。它完全依赖于调用它的代码。

    所以如果闭包需要额外的“参数”,你只需要把它们放在作用域内:

    doSomething(function ($result) use ($importantData) {
      doSomethingElse($result, $importantData);
    });
    

    【讨论】:

      猜你喜欢
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 2015-01-04
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多