提问人:pilotman 提问时间:4/20/2021 更新时间:4/20/2021 访问量:50
PHP Closure 的错误响应
Wrong response from PHP Closure
问:
我试图更多地理解闭包,但我无法从下面的代码中得到正确的响应。出于某种原因,我得到的回复是 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();
答:
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()
$c
getEntry()
评论
getEntry
PHP Notice: Object of class Closure could not be converted to int