How Can Lambda Functions in PHP Access and Modify External Variables?

Linda Hamilton
Release: 2024-11-11 12:26:03
Original
866 people have browsed it

How Can Lambda Functions in PHP Access and Modify External Variables?

Using Lambda Functions to Access External Variables

In PHP, it is possible to access external variables within lambda functions, providing flexibility in data processing. However, understanding the nuances of variable capturing is crucial.

Consider the code snippet:

function fetch($query, $func) {
    $query = mysql_query($query);
    while($r = mysql_fetch_assoc($query)) {
        $func($r);
    }
}

fetch("SELECT title FROM tbl", function($r){
   //> $r['title'] contains the title
});
Copy after login

This code allows us to process database rows using a provided function. However, if we need to aggregate data from multiple rows, we can use the use keyword within the lambda function.

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

echo $result;
Copy after login

By adding use (&$result), we tell the lambda function to use the external $result variable and pass it by reference (&). This allows us to concatenate values from each row into a single variable.

It's important to note that lambda functions use early binding, capturing the value of external variables when the function is defined, not when it's called. This can lead to unexpected behavior when the external variable changes value between declaration and invocation.

The above is the detailed content of How Can Lambda Functions in PHP Access and Modify External Variables?. 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