Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variables in anonymous functions

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?

like image 202
einord Avatar asked Jul 10 '12 19:07

einord


People also ask

How do you use variables in anonymous functions?

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

How can you pass a local variable to an anonymous function in 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 & . It's new!

Which statement is not allowed in anonymous function in PHP?

As of PHP 7.1, these variables must not include superglobals, $this , or variables with the same name as a parameter.

Can an anonymous function be assigned to a variable?

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.


1 Answers

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

like image 192
nickb Avatar answered Oct 05 '22 22:10

nickb