Home > Article > Backend Development > How Can Lambda Functions in PHP Access and Modify External Variables?
Using Lambda Functions to Access External Variables
In PHP, it is possible to access external variables within lambda functions, providing flexibility in data processing. However, understanding the nuances of variable capturing is crucial.
Consider the code snippet:
function fetch($query, $func) { $query = mysql_query($query); while($r = mysql_fetch_assoc($query)) { $func($r); } } fetch("SELECT title FROM tbl", function($r){ //> $r['title'] contains the title });
This code allows us to process database rows using a provided function. However, if we need to aggregate data from multiple rows, we can use the use keyword within the lambda function.
$result = ''; fetch("SELECT title FROM tbl", function($r) use (&$result) { $result .= $r['title']; }); echo $result;
By adding use (&$result), we tell the lambda function to use the external $result variable and pass it by reference (&). This allows us to concatenate values from each row into a single variable.
It's important to note that lambda functions use early binding, capturing the value of external variables when the function is defined, not when it's called. This can lead to unexpected behavior when the external variable changes value between declaration and invocation.
The above is the detailed content of How Can Lambda Functions in PHP Access and Modify External Variables?. For more information, please follow other related articles on the PHP Chinese website!