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

。_饼干妹妹 提交于 2019-11-29 06:18:48

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!