Consider the following code:
$external_variable = TRUE;
usort($array, function($a, $b) {
// do sorting stuff based on $external_variable
});
How can I access and use $external_variable within the usort function?
Consider the following code:
$external_variable = TRUE;
usort($array, function($a, $b) {
// do sorting stuff based on $external_variable
});
How can I access and use $external_variable within the usort function?
Using the use
keyword:
$external_variable = TRUE;
usort($array, function($a, $b) use($external_variable) {
// do sorting stuff based on $external_variable
});
http://php.net/manual/en/functions.anonymous.php
Closures may also inherit variables from the parent scope. Any such variables must be passed to the
use
language construct. From PHP 7.1, these variables must not include superglobals,$this
, or variables with the same name as a parameter.