PHP variables in anonymous functions PHP variables in anonymous functions php php

PHP variables in anonymous functions


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


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");