Use variables inside an anonymous function, which is defined somewhere else

后端 未结 2 1730
野的像风
野的像风 2020-12-17 18:29

When using anonymous functions in PHP, you can easily use variables from right outside of its scope by using the use() keyword.

In my case the anonymous

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 18:46

    The point of the use keyword is to inherit/close over a particular environment state from the parent scope into the Closure when it's defined, e.g.

    $foo = 1;
    
    $fn = function() use ($foo) {
        return $foo;
    };
    
    $foo = 2;
    
    echo $fn(); // gives 1
    

    If you want $foo to be closed over at a later point, either define the closure later or, if you want $foo to be always the current value (2), pass $foo as a regular parameter.

提交回复
热议问题