【问题标题】:Wrong response from PHP ClosurePHP Closure 的错误响应
【发布时间】:2021-07-14 00:10:37
【问题描述】:

我试图更多地理解闭包,但我无法从下面的代码中得到正确的响应。由于某种原因,我得到了 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();

【问题讨论】:

  • getEntry 方法上,你得到$b 和$c 的总和。你在第二个参数上传递了一个闭包,所以它变成了闭包 + 30。如果你允许在你的错误冗长中通知你,你会得到一个 PHP Notice: Object of class Closure could not be converted to int 通知,并将闭包解释为 1,这就是你得到 31 的原因。

标签: php closures anonymous-function


【解决方案1】:

在函数getEntry()中,$b不是整数,而是函数。需要调用$b()来执行这个函数才能得到结果:

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

这里,$b() 将返回 30,$c 等于 30。因此,getEntry() 将返回 60。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 2017-10-04
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多