I'll-Be-Back
I'll-Be-Back

Reputation: 10828

Assign the value from callback to variable?

I am having problem to assign the value from callback to variable.

Example code below, that work without any issue. It will display on the browser.

Service::connect($account)->exec(['something'], function ($line) {
   echo $line . PHP_EOL;
});

However, I want to assign to variable for json response.

This does not work:

$outout = null;

Service::connect($account)->exec(['something'], function ($line) use ($outout) {
      $outout = $outout . = $line;
);

echo $outout;

The $outout is still null.

What did I do wrong?

Upvotes: 1

Views: 212

Answers (2)

daker
daker

Reputation: 3540

Pass $outout as a reference if you want it to change outside the scope of your function. You do that by adding & in your function call.

$outout = '';
Service::connect($account)->exec(['something'], function ($line) use (&$outout) {
      $outout = $outout . = $line;
); 

Upvotes: 2

Elias Soares
Elias Soares

Reputation: 10254

You need to pass it as reference to change it value. Use an & before your variable on use statement.

$outout = null;

Service::connect($account)->exec(['something'], function ($line) use (&$outout) {
      $outout = $outout . = $line;
);

echo $outout;

Upvotes: 1

Related Questions