PHP variables in anonymous functions

PhpFunctionVariablesGlobal VariablesAnonymous

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

If your function is short and one-linear, you can use arrow functions, as of PHP 7.4:

$variable = "nothing";
functionName($someArgument, fn() => $variable = "something");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioneinordView Question on Stackoverflow
Solution 1 - PhpnickbView Answer on Stackoverflow
Solution 2 - PhpMAChitgarhaView Answer on Stackoverflow