PHP variables in anonymous functions

53,559

Solution 1

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

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");
Share:
53,559
einord
Author by

einord

Started programming with QBasic at the age of twelve on an old 386 PC with DOS, and have been working professionally with software development since 2010.

Updated on September 16, 2021

Comments

  • einord
    einord over 2 years

    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?

  • gen_Eric
    gen_Eric almost 12 years
    It's new! It's syntax that's new in PHP 5.3.
  • DaveRandom
    DaveRandom almost 12 years
    @Rocket So, to be fair, is the true anonymous function syntax (as opposed to create_function()) and the use keyword is documented (badly) on the same doc page that describes them.
  • keyboardSmasher
    keyboardSmasher over 10 years
    Quick note for those who may not know: You can drop the & when passing an object, since they are always passed by reference...and don't forget your type-hint :) E.g.: function() use (PDO $pdo) {
  • nickb
    nickb over 6 years
    @Alliswell No, it's only for objects, otherwise you need to pass by reference to modify the variable. See this example.