157

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?

0

1 Answer 1

372

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.