Reputation: 675
I trying to understand closures more but I cannot get the correct response from the below code. I get a response of 31 instead of 60 for some reason. My aim is to eventually start unit testing closures.
Thanks
<?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();
Upvotes: 0
Views: 53
Reputation: 19764
In the function getEntry()
, $b
is not an integer, but a function. You need to execute this function by calling $b()
to get the result:
private function getEntry($a, $b, $c)
{
return $b() + $c; // instead of `$b + $c`
}
Here, $b()
will return 30, and $c
is equal to 30. So, getEntry()
will return 60.
Upvotes: 3