如何访问symfony2中setCallback函数外部的变量


How to access a variable outside setCallback function in symfony2?

我知道如何在setCallback函数之外设置变量的值,并在其中使用它。

$response = new StreamedResponse();  
$i = 0;  
$params = "hello";
$response->setCallback(function () use ($params){  
    while($i < 999999){  
        echo 'Something';  
        $i = $i + 1;  
    }  
});  

即通过使用CCD_ 1
我想从这个回调函数中设置一个变量的值,并想在函数外使用它。如果不使用全局变量,我如何实现这一点?

$response = new StreamedResponse();  
$i = 0;  
$params = "hello";
$response->setCallback(function () use ($params){
// --- Set variable here ---  
    while($i < 999999){  
      echo 'Something';  
      $i = $i + 1;  
    }  
}); 
 -- Use variable here ---

我尝试了以下代码,但不起作用-

$response = new StreamedResponse();
$format = "json";
$response->setCallback(function () use(&$format) {
    $format = "xml"; 
    echo $format; //prints xml
});
echo $format; //prints json

您可以使用&运算符在use语句中通过引用传递变量:

<?php
$foo = 0;
$closure = function() use (&$foo) {
    $foo = 5;
};
$closure();
echo "$foo"; // will output "5"