在匿名函数中使用变量,这是在其他地方定义的 [英] Use variables inside an anonymous function, which is defined somewhere else

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

问题描述

在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()关键字从方法中获取 $ arg $ c>这种方式。因为<$>匿名功能是在方法之外声明的。

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆