php 使用匿名函数作为参数访问外部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8403908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing outside variable using anonymous function as params
提问by dynamic
Basically I use this handy function to processing db rows (close an eye on PDO and/or other stuff)
基本上我使用这个方便的函数来处理数据库行(密切关注 PDO 和/或其他东西)
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
});
Let's say now I need to concatenate all $r['title']
in a var (this is just an example).
假设现在我需要将所有内容连接$r['title']
到一个 var 中(这只是一个示例)。
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;
回答by Xaerxess
You have to use use
as described in docs:
你必须使用use
如在文档中所述:
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.
闭包也可以从父作用域继承变量。任何此类变量都必须在函数头中声明。从父作用域继承变量与使用全局变量不同。全局变量存在于全局作用域中,无论执行什么函数都是一样的。
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() 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).
use() 参数是早期绑定——它们在声明 lambda 函数的地方使用变量的值,而不是在调用 lambda 函数的地方(后期绑定)。
回答by user103307
What about rewriting 'fetch' to call $func only once ?
重写 'fetch' 只调用一次 $func 怎么样?
function fetch($query,$func) {
$query = mysql_query($query);
$retVal = array();
while($r = mysql_fetch_assoc($query)) {
$retVal[] = $r;
}
$func($retVal);
}
This way you would call $func only once and re-process the array once fetched? Not sure about the performance even tho calling 200 times a function doesn't sound like a good idea.
这样你只会调用 $func 一次并在获取后重新处理数组?即使调用一个函数 200 次,也不确定性能听起来不是一个好主意。