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

后端 未结 2 1725
野的像风
野的像风 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:40

    FWIW, you can do it if you use a use reference (php.net ex 3.3) and a global, ugly since it uses globals, but just to put it out there:

    <?php
    $bla = function ( $var1 ) use (&$arg)
            {
                return "var1:$var1, arg:$arg";
            };
    
    class MyClass
    {
        private $func;
    
        public function __construct ( $func )
        {
            $this->func = $func;
        }
    
        public function test ( $param )
        {
            global $arg;
            $arg=$param;
            $closure =  $this->func;
            return  $closure ( 'anon func' );
        }
    }
    
    $c = new MyClass($bla);
    echo $c->test ( 'bla bla' ); //var1:anon func, arg:bla bla
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题