0

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();
1
  • 1
    on getEntry method, you are getting the sum of $b and $c. You passed a closure on the second argument so it becomes closure + 30. If you allow notices in your error verbosity you will get a PHP Notice: Object of class Closure could not be converted to int notice, and interprets the closure as 1, that's why you're getting 31. Commented Apr 19, 2021 at 19:21

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.