如何在 PHP 中的匿名函數中存取和修改外部變數?

DDD
發布: 2024-11-14 17:56:02
原創
794 人瀏覽過

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'];
});
登入後複製

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板