Comment puis-je accéder et modifier des variables externes dans une fonction anonyme en PHP ?

DDD
Libérer: 2024-11-14 17:56:02
original
795 Les gens l'ont consulté

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'];
});
Copier après la connexion

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal