PHP Closure 的错误响应

Wrong response from PHP Closure

提问人:pilotman 提问时间:4/20/2021 更新时间:4/20/2021 访问量:50

问:

我试图更多地理解闭包,但我无法从下面的代码中得到正确的响应。出于某种原因,我得到的回复是 31 而不是 60。我的目标是最终开始单元测试闭包。

谢谢


<?php


class Closuretest
{

    /**
     * Closuretest constructor.
     */
    public function __construct()
    {
    }

    /**
     * @return mixed
     */
    public function getToken()
    {


            $response = $this->getEntry('abcde', function() {
                return 30;
            }, 30);

        // Return access token
        return $response;
    }


    /**
     * @param $a
     * @param $b
     * @param $c
     * @return mixed
     */
    private function getEntry($a, $b, $c)
    {
        return $b+$c;
    }

}

$testinstance = new Closuretest();

echo $testinstance->getToken();
PHP 闭包 匿名函数

评论

1赞 rai 4/20/2021
在方法上,您将获得 $b 和 $c 的总和。您在第二个参数上传递了一个闭包,因此它变为闭包 + 30。如果你允许在错误冗长中发出通知,你会得到一个通知,并将闭包解释为 1,这就是你得到 31 的原因。getEntryPHP Notice: Object of class Closure could not be converted to int

答:

3赞 Syscall 4/20/2021 #1

在函数中,不是整数,而是函数。您需要通过调用来执行此函数以获取结果:getEntry()$b$b()

private function getEntry($a, $b, $c)
{
    return $b() + $c; // instead of `$b + $c`
}

在这里,将返回 30,等于 30。所以,将返回 60。$b()$cgetEntry()