Problem Statement:
You have a reusable function fetch that processes database rows and allows you to perform operations on each row using an anonymous function. However, you need to concatenate a specific field from all the rows into a single variable within the anonymous function.
Solution:
To access an outside variable within an anonymous function, you can use the use keyword. This will inherit the variable from the parent scope.
Example:
$result = ''; fetch("SELECT title FROM tbl", function($r) use (&$result) { $result .= $r['title']; });
How it Works:
Note:
The above is the detailed content of How to Access External Variables within Anonymous Functions in PHP?. For more information, please follow other related articles on the PHP Chinese website!