使用匿名函数作为参数访问外部变量 [英] Accessing outside variable using anonymous function as params

查看:140
本文介绍了使用匿名函数作为参数访问外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我使用这个方便的函数来处理db行(关注PDO和/或其他东西)

Basically I use this handy function to processing db rows (close an eye on PDO and/or other stuff)

function fetch($query,$func) {
    $query = mysql_query($query);   
    while($r = mysql_fetch_assoc($query)) {
        $func($r);
    }
}

使用此函数我可以简单地做:

With this function I can simply do:

fetch("SELECT title FROM tbl", function($r){
   //> $r['title'] contains the title
});

现在我需要连接所有 $ r ['title'] 在一个var(这只是一个例子)。

Let's say now I need to concatenate all $r['title'] in a var (this is just an example).

我该怎么办?我在想这样的东西,但它不是很优雅:

How could I do that? I was thinking something like this, but it's not very elegant:

$result = '';
fetch("SELECT title FROM tbl", function($r){
   global $result;
   $result .= $r['title'];
});

echo $result;


推荐答案

您必须使用 use ,如在文档中所述:

You have to use use as described in docs:


闭包也可以从父作用域继承变量。任何这样的
变量必须在函数头中声明。从父作用域继承
变量与使用全局
变量不同。全局变量存在于全局范围中,即
相同,不管什么函数正在执行。

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing.

代码: p>

Code:

$result = '';
fetch("SELECT title FROM tbl", function($r) use (&$result) {
   $result .= $r['title'];
});

但请注意(取自上一个链接中的评论之一):

But beware (taken from one of comments in previous link):


use()参数是早期绑定 - 它们使用变量的值
声明lambda函数的点,而不是点
调用lambda函数(后期绑定)。

use() parameters are early binding - they use the variable's value at the point where the lambda function is declared, rather than the point where the lambda function is called (late binding).

这篇关于使用匿名函数作为参数访问外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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