user2019515
user2019515

Reputation: 4503

Return value from anonymous function to parent function

I have a setup like this:

function test(){
    function(){
        return "testing!";
    };
    return;
}

echo test();

And I'm trying to get the test() function to return "testing" (in this example) but that doesn't work. What would you advice?

Why are you using an anonymouse function? I have to use an anonymous function for this because I'm using the HttpClient of ReactPHP, here's a basic example of how that works:

$request = $client->request('GET', 'https://api.github.com/repos/reactphp/react/commits');
$request->on('response', function ($response) {
    $buffer = '';

    $response->on('data', function ($data) use (&$buffer) {
        $buffer .= $data;
        echo ".";
    });

    $response->on('end', function () use (&$buffer) {
        $decoded = json_decode($buffer, true);
        $latest = $decoded[0]['commit'];
        $author = $latest['author']['name'];
        $date = date('F j, Y', strtotime($latest['author']['date']));

        echo "\n";
        echo "Latest commit on react was done by {$author} on {$date}\n";
        echo "{$latest['message']}\n";
    });
});
$request->on('end', function ($error, $response) {
    echo $error;
});
$request->end();

In the example above they echo the content of the page, but I'd like to return it instead, any help would be much appreciated. Thanks!

Upvotes: 0

Views: 661

Answers (2)

Will
Will

Reputation: 7245

How about call_user_func?

function test(){
    return call_user_func(function(){
        return "testing!";
    });
}

echo test();

According to the docs:

Return Values

Returns the return value of the callback, or FALSE on error.

Further Reading

call_user_func documentation

Edit:

I suggest you look into using a different library for your http requests that is not asynchronous.

Alternatively you can do some busy waiting while you wait for the request to complete. To do this have a variable in the outermost scope set to null. Set this variable to the request's result once you get it. After you've set up all the callbacks keep checking the variable for something other than null (sleep in between checks). Also set a callback on error to set this variable to something like false so that the program can get out of the loop if it fails.

Upvotes: 2

user229044
user229044

Reputation: 239402

You can't. That's impossible. You have to return the value to the outer function, which must then return its own value:

function test(){
    $fn = function(){
        return "testing!";
    };

    return $fn();
}

Your inner function doesn't get to return out of the outer function.

Upvotes: 1

Related Questions