Search code examples
phpclosures

In PHP, what is a closure and why does it use the "use" identifier?


I'm checking out some PHP 5.3.0 features and ran across some code on the site that looks quite funny:

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);
}

as one of the examples on anonymous functions.

Does anybody know about this? Any documentation? And it looks evil, should it ever be used?


Solution

  • This is how PHP expresses a closure. This is not evil at all and in fact it is quite powerful and useful.

    Basically what this means is that you are allowing the anonymous function to "capture" local variables (in this case, $tax and a reference to $total) outside of it scope and preserve their values (or in the case of $total the reference to $total itself) as state within the anonymous function itself.