How to Access External Variables within Anonymous Functions in PHP?

Patricia Arquette
Release: 2024-11-11 12:36:02
Original
801 people have browsed it

How to Access External Variables within Anonymous Functions in PHP?

Accessing Outside Variables Using Anonymous Functions as Parameters

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'];
});
Copy after login

How it Works:

  • The use keyword is used within the anonymous function's parameter list.
  • It declares that the variable $result should be inherited from the parent scope.
  • By using the & symbol in the use statement, the variable is passed by reference, allowing the anonymous function to modify its value.

Note:

  • use variables are early bound, meaning they use the value of the variable at the time the anonymous function is declared, not when it is called.
  • This could lead to unexpected behavior if the value of the variable is modified after the anonymous function is defined.

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template