1

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 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.

1
  • this might not exactly answer your question, but why you don't use return $variable; or global? or return array if you need some bunch of variables to change. Commented Aug 7, 2011 at 6:32

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Very good answer from Matthey Scharley. To read about php referencing see this: php.net/manual/en/language.references.php
0

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.

3 Comments

Please don't do this... do it properly and just pass the variable by reference. Is there some reason you can't do this?
Why I should not do it ? This is my code and it would be closure in a function so everything is protected from spill. The reason is that I must also know the variable name, so if there was an error I could post a message what variable is wrong.
Globals are just that: global. Their scope is the entire program. Entirely aside from that, it's harder for tools to track things if you start passing around strings with variable and function names in them and use those as 'references'. Part of the reason that closures were introduced with 5.3 was to try to get away from the so-called 'callback' types used in PHP (strings that happen to contain function names).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.