Rick
Rick

Reputation: 711

PHP access variable from inside an anonymous function callback on the outside?

Is there a way to get the $value seen below so that it can be used in the var_dump?

// can't alter this function..
function test($callback) {
    $callback('test');
}

// can alter this in any way so long as the above function still works..
test(function ($value) {
    return $value; // how to get $value for the dump below?
});

var_dump($value); // expecting "test"

Upvotes: 0

Views: 37

Answers (1)

Jeto
Jeto

Reputation: 14927

You'd have to use a separate variable and pass it as context to the closure via reference, using use and &:

function test($callback)
{
  $callback('test');
}

test(function ($value) use (&$result) {
  $result = $value;
});

echo $result; // 'test'

Demo: https://3v4l.org/OlBHU

Upvotes: 1

Related Questions