155

I was playing around with anonymous functions in PHP and realized that they don't seem to reach variables outside of them. Is there any way to get around this problem?

Example:

$variable = "nothing";

functionName($someArgument, function() {
  $variable = "something";
});

echo $variable;  //output: "nothing"

This will output "nothing". Is there any way that the anonymous function can access the $variable?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
einord
  • 2,278
  • 2
  • 20
  • 26

1 Answers1

368

Yes, use a closure:

functionName($someArgument, function() use(&$variable) {
  $variable = "something";
});

Note that in order for you to be able to modify $variable and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using &.

miken32
  • 42,008
  • 16
  • 111
  • 154
nickb
  • 59,313
  • 13
  • 108
  • 143