Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

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

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 functions are already defined somewhere, but called later on (somewhere else) in a class.

The following piece of code is to illustrate the idea:

<?php

$bla = function ( $var1 ) use ($arg)
        {
            echo $var1;
        };

class MyClass
{
    private $func;

    public function __construct ( $func )
    {
        $this->func = $func;
    }

    public function test ( $arg )
    {
        $closure =  $this->func;
        $closure ( 'anon func' );
    }
}

$c = new MyClass($bla);
$c->test ( 'anon func' );

What i'm doing is i create an anonymous function and store that in a variable. I pass that variable to the method of a class and that is where i want to run the anonymous function.

But i can't use the use() keyword to get the $arg parameter from the method this way. Because the anonymous function was declared outside of the method.

But i really need a way to get the variables from the method where the anonymous function is run from. Is there a way to do that, when the anonymous function is declared somewhere else..?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...