[英]PHP Variable scope: Pass parameter by reference with default value to anonymous function?
I'm trying to loop through a mysql result and run an anonymous function on each record, but I'm having some trouble with variable scope. 我试图遍历一个mysql结果并在每条记录上运行一个匿名函数,但是我在变量范围方面遇到了一些麻烦。 The problem is part of a much bigger flow but I've created a simplified example here which demonstrates the issue simply:
这个问题是更大流程的一部分,但是我在这里创建了一个简化的示例,简单地演示了该问题:
function runLoop($some_mysql_resource){
$res = 'RESULTS: ';
sqlEach($some_mysql_resource, function($sql){
$res .= $sql['id'].',';
})
return $res;
);
Is there any way to make the runLoop function above output the following without changing the logical flow? 有什么方法可以使上面的runLoop函数在不更改逻辑流程的情况下输出以下内容?
RESULTS: 1,2,3,4,etc...
Pass $res
as an argument "by reference" to your callback using use
使用
use
$res
作为参数“通过引用”传递给您的回调
function runLoop($some_mysql_resource){
$res = 'RESULTS: ';
sqlEach($some_mysql_resource, function($sql) use (&$res) {
$res .= $sql['id'].',';
})
return $res;
);
I assume that $sql
is defined somewhere in your real code, and so will have scope 我假设
$sql
是在您的真实代码中定义的,因此具有作用域
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.