2

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?

CGriffin
  • 1,406
  • 15
  • 35

1 Answers1

6

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.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368