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']; });
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.
以上是如何在 PHP 中的匿名函數中存取和修改外部變數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!