【发布时间】: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