PHP Functional Programming Using outside variables


Example

The use construct is used to import variables into the anonymous function's scope:

$divisor = 2332;
$myfunction = function($number) use ($divisor) {
    return $number / $divisor;
};

echo $myfunction(81620); //Outputs 35

Variables can also be imported by reference:

$collection = [];

$additem = function($item) use (&$collection) {
    $collection[] = $item;
};

$additem(1);
$additem(2);

//$collection is now [1,2]