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
?
$var=function ($arg1, $arg2) { return $val; }; There is no function name between the function keyword and the opening parenthesis. There is a semicolon after the function definition because anonymous function definitions are expressions. Function is assigned to a variable, and called later using the variable's name.
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 & . It's new!
As of PHP 7.1, these variables must not include superglobals, $this , or variables with the same name as a parameter.
An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With