开发者

is it possible to reach out of closure scope in php and access variable by reference?

example:

$my_var = 'some text';
$my_closure = function($variable_name) {
  //here some magic...
  $$variable_name = 'some other text';
};
$my_closure('my_var');
echo $my_var //-> 'some other text';

the only way I know now is by using compact() or use() in the closure 开发者_JS百科declaration, but compact look like this extract($my_closure(compact('my_var'))); and use must be done when closure is declared so is not flexible.


You do it the same as any other function, you declare the parameter as pass-by-reference:

$my_var = 'some text';
$my_closure = function(&$var) {
  $var = 'some other text';
};
$my_closure($my_var);
echo $my_var."\n";

Allowing arbitrary access to the calling scope is far too dangerous though and would lead to too many issues. Closures in languages in general, not just PHP, are designed to be able to access private/local variables in the scope they were defined in (use() in PHP), but I can't think of a single one that allows them to arbitrarily access locals in the calling scope (even other scripting languages).


finally found it and I am baffled that it was so obvious:

$outside_var = 'wrong';
$closure = function($var_name,$new_value) {
  global $$var_name; // SO OBVIOUS!!!
  $$var_name = $new_value;
};

echo $outside_var."\n";
$closure('outside_var','right');
echo $outside_var."\n";

Unfortunately the limitation is that variable must be declared before closure, otherwise the variable is NULL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜