Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing outside variable using anonymous function as params

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 }); 

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; 
like image 733
dynamic Avatar asked Dec 06 '11 17:12

dynamic


People also ask

Can anonymous functions have parameters?

An anonymous function is a function with no name which can be used once they're created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function.

How do you access a variable outside a function?

1 Answer. Using the keyword "global", you can change the scope of a variable from local to global, and then you can access it outside the function. E.g. The following code will print v =25 although the print statement is outside the function.

How do you use variables in anonymous functions?

$var=function ($arg1, $arg2) { return $val; }; There is no function name between the function keyword and the opening parenthesis. There is a semicolon after the function definition because anonymous function definitions are expressions. Function is assigned to a variable, and called later using the variable's name.

Can you assign an anonymous function to a variable and pass it as an argument to another function?

They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.


1 Answers

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.

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).

like image 102
Xaerxess Avatar answered Sep 24 '22 20:09

Xaerxess