如何在symfony2中访问setCallback函数之外的变量?
问题描述:
我知道如何在setCallback函数外设置一个变量的值并在其中使用它。如何在symfony2中访问setCallback函数之外的变量?
$response = new StreamedResponse();
$i = 0;
$params = "hello";
$response->setCallback(function() use ($params){
while($i < 999999){
echo 'Something';
$i = $i + 1;
}
});
即通过使用use
。
我想从这个回调函数中设置一个变量的值,并希望在函数外部使用它。我怎样才能实现这一点,而不使用全局变量?
$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"
感谢。如果我传递一个参数数组而不是单个变量,应该如何传递变量? – User42
如果您有多个参数,则必须在每个参数前加一个&符号:'... use(&$ one,&$ two,&$ three)'。无论参数是否是数组都不重要,只需使用它就像一个“正常”变量。 – hanzi
你的代码工作正常,但这种技术不适合我。我正尝试在StreamedResponse的setCallback()函数中设置一个变量的值。请确认。编辑了这个问题。 – User42