Callback Function Utilizing Variables Outside Its Scope
In PHP, it is often desirable to utilize callback functions that operate on data defined outside their immediate scope. To achieve this, the use keyword can be employed to explicitly import these variables.
In the provided example, an array $arr is initialized, and its average ($avg) is calculated. However, within the anonymous callback function $callback, we encounter an issue as $avg is not defined.
To resolve this, we can leverage the use keyword:
1 |
|
By adding use ($avg), the $avg variable from the parent scope is imported into the callback function, allowing us to use it in our calculation.
Another approach available in PHP 7.4 and later is the use of arrow functions:
1 |
|
Arrow functions automatically capture outside variables, streamlining the process. Alternatively, we can simplify further and include the callback definition directly within the array_filter call:
1 |
|
This demonstrates the versatility of PHP in addressing the need to use variables calculated outside of callback functions.
The above is the detailed content of How Can I Access Variables Outside a Callback Function's Scope in PHP?. For more information, please follow other related articles on the PHP Chinese website!