本文介绍了在匿名函数中使用变量,该函数在其他地方定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 中使用匿名函数时,您可以通过使用 use() 关键字轻松地从其作用域之外使用变量.

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.

但是我不能使用 use() 关键字以这种方式从 method 获取 $arg 参数.因为匿名函数是在method之外声明的.

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..?

推荐答案

use 关键字的重点是 从父作用域继承/关闭一个特定的环境状态 到闭包定义时,例如

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

如果您希望 $foo 在稍后关闭,请稍后定义闭包,或者,如果您希望 $foo 始终为当前值 (2)、将$foo作为常规参数传递.

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.

这篇关于在匿名函数中使用变量,该函数在其他地方定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:40