相关疑难解决方法(0)

使用匿名函数作为参数访问外部变量

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

function fetch($query,$func) {
    $query = mysql_query($query);   
    while($r = mysql_fetch_assoc($query)) {
        $func($r);
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个功能,我可以简单地做到:

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

现在假设我需要$r['title']在var中连接所有内容(这只是一个例子).

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

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

echo $result;
Run Code Online (Sandbox Code Playgroud)

php closures scope

89
推荐指数
1
解决办法
4万
查看次数

标签 统计

closures ×1

php ×1

scope ×1