As a general rule when creating a Closure, arguments are passed when the function is called, but “use” variables (I’m sure that they have a formal name, but have no idea what it might be, so I just refer to them as “use” variables because they’re passed to the Closure through a “use” clause) are fixed as the value that they already contain when the Closure is defined, and the variables themselves must already exist within that scope. This isn’t normally a problem where we’re defining the Anonymous function inline, because we can specify the values directly in the callback function itself:
$filteredArrayData = array_filter(
$arrayData,
function($value) { return $value->price >= 120.00 && $value->price < 250.00; }
);
Writing our callbacks like this has the big benefit of being easy to read and understand exactly what the callback is doing.
Of course, the drawback of this approach is that when we need to change the price minimum and maximum values for filtering, they’re hard-coded in the callback.
For those array functions that use callbacks, such as array_filter(), we can’t simply pass the values as extra parameters directly to the function; although we can define the price range values as variables that can then be passed to the callback function as “use” variables. Perhaps a more practical approach than hard-coding them if we get the minimum and maximum values for filtering from user input, or if they need to be calculated elsewhere in our code.
$minimumPrice = 120.00;
$maximumPrice = 250.00;
$filteredArrayData = array_filter(
$arrayData,
function($value) use ($minimumPrice, $maximumPrice) {
return $value->price >= $minimumPrice && $value->price < $maximumPrice;
}
);
Continue reading →