phpscopeanonymous-function

PHP function use(*) all


I often pass local variables to functions declared in variables like:

public function getTotal($tax)
{
    $total = 0.00;

    $callback =
        /* This line here: */
        function ($quantity, $product) use ($tax, &$total)
        {
            $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                strtoupper($product));
            $total += ($pricePerItem * $quantity) * ($tax + 1.0);
        };

    array_walk($this->products, $callback);
    return round($total, 2);
}

Is it possible to pass every local variable that is declared in the same scope as declared function without listing them all like use($a,$b,$c ...)?

So if I would like like use(*) everything that was accessable in parent scope will be passed to declared function scope?


Solution

  • Closures should be very limited in what they do. 4-5 lines tops really.

    In my mind, it is far better to define the variables being made available to it as closures are essentially unstructured.

    I usually inline them like this though:

    array_walk($this->products, function ($quantity, $product) use ($tax, &$total) {
    
    });
    

    The new operation of the use keyword might be a bit cumbersome, but it is better than global. This is a much more manageable can of worms.