2017-04-04 155 views
1

我有问题将值从回调分配给变量。将回调值赋给变量?

下面的示例代码,该工作没有任何问题。它将显示在浏览器上。

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

但是,我想分配给变量的JSON响应。

这不起作用:

$outout = null; 

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

echo $outout; 

$outout仍然是空。

我做错了什么?

+0

可能重复[在PHP关闭使用关键字传递引用?](http://stackoverflow.com/questions/10869572/does-the-use-keyword-in-php-closures-pass -by-reference) – miken32

回答

2

通过$outout作为reference如果你想它改变你的功能范围之外。你可以在你的函数调用中加入&

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

是的,那是从父范围继承一个变量,而不是相反。在这里寻找一个参考http://php.net/manual/en/functions.anonymous.php – daker

1

你需要通过它作为参考来改变它的值。在您的变量use声明之前使用&

$outout = null; 

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

echo $outout;