explain what is a closure in PHP and why does it use the “use” identifier?

Technology CommunityCategory: PHPexplain what is a closure in PHP and why does it use the “use” identifier?
VietMX Staff asked 3 years ago
Problem

Consider this code:

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

    $callback =
        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);
}

Could you explain why use it?

This is how PHP expresses a closure. Basically what this means is that you are allowing the anonymous function to “capture” local variables (in this case, $tax and a reference to $totaloutside 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.

A closure is a separate namespace, normally, you can not access variables defined outside of this namespace.

  • use allows you to access (use) the succeeding variables inside the closure.
  • use is early binding. That means the variable values are COPIED upon DEFINING the closure. So modifying $tax inside the closure has no external effect, unless it is a pointer, like an object is.
  • You can pass in variables as pointers like in case of &$total. This way, modifying the value of $total DOES HAVE an external effect, the original variable’s value changes.