Home > Backend Development > PHP Tutorial > How Can I Access External Variables Inside PHP Callback Functions?

How Can I Access External Variables Inside PHP Callback Functions?

Mary-Kate Olsen
Release: 2024-12-14 20:33:41
Original
779 people have browsed it

How Can I Access External Variables Inside PHP Callback Functions?

Accessing External Variables within Callback Functions

In PHP, it is often necessary to utilize callback functions in conjunction with variables calculated outside of the function's scope. This scenario raises the question: Is it possible to access such variables within the callback?

The Use Keyword and Arrow Functions

Fortunately, PHP provides a solution through the use keyword. You can inherit variables from the parent scope by prefacing the callback definition with use. For instance:

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$avg = array_sum($arr) / count($arr);
$callback = function($val) use ($avg) { return $val < $avg; };

return array_filter($arr, $callback);
Copy after login

For PHP versions 7.4 and later, arrow functions offer a more elegant approach. Arrow functions automatically capture outside variables:

$callback = fn($val) => $val < $avg;
Copy after login

Within the array_filter call, you can directly utilize the arrow function:

return array_filter($arr, fn($val) => $val < $avg);
Copy after login

By leveraging the use keyword or arrow functions, it becomes straightforward to access external variables within callback functions in PHP.

The above is the detailed content of How Can I Access External Variables Inside PHP Callback Functions?. 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