Access an external variable using an anonymous function as parameters

I mainly use this handy function to handle db strings (close your eyes to PDO and / or other things)

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 combine all $r['title'] into var (this is just an example).

How could I do this? I thought something like this, but it is not very elegant:

 $result = ''; fetch("SELECT title FROM tbl", function($r){ global $result; $result .= $r['title']; }); echo $result; 
+69
scope closures php
Dec 06 '11 at 17:11
source share
2 answers

You should use use as described in the docs :

Closing can also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheritance variables from the parent scope do not match using global variables. Global variables exist on a global scale, regardless of what function performs.

the code:

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

But be careful (taken from one of the comments in the previous link):

Options

use () are early relationships - they use the value of the variable to the point where the lambda function is declared, not the point where the lambda function is called (late binding).

+135
Dec 06 '11 at 17:15
source share

How about rewriting 'fetch' to call $ func only once?

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

So you could only call $ func once and re-process the array after retrieval? Not sure about performance even when called 200 times, the function doesn't look like a good idea.

0
Dec 6 '11 at 17:20
source share



All Articles