How can I access and modify external variables within an anonymous function in PHP?

DDD
Release: 2024-11-14 17:56:02
Original
802 people have browsed it

How can I access and modify external variables within an anonymous function in PHP?

Using Anonymous Functions as Parameters to Access External Variables

The scenario involves a handy function that conveniently processes database rows. However, a specific requirement arises where you need to concatenate all titles from the result set into a single variable. This raises the question of how to accomplish this without relying on the less elegant approach of using the global keyword.

One solution lies in the use of closure variables. Specifically, the use keyword allows closures to inherit variables from the parent scope. This is different from global variables, which persist across all functions.

To implement this solution, the code can be modified as follows:

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

By adding use (&$result) to the anonymous function, we are able to reference and modify the result variable from within the function. The use keyword effectively passes a reference to the result variable to the closure.

It's important to note that this approach involves early binding, which means that the closure uses the value of the variable at the point of function declaration, not at the point of function call (late binding). This is something to keep in mind when utilizing closures for this purpose.

The above is the detailed content of How can I access and modify external variables within an anonymous function in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template