What is the benefit of using closures in PHP?

4

Eg: Why use a closure for this function:

We could do the same thing without a closure, but why use this class?

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

link

    
asked by anonymous 09.07.2014 / 21:32

1 answer

7

Marcelo,

In my experience with javascript and c # I could say that Clousure is used to explore aspects of scope and context.

In javascript and other languages that allow event-driven (like C #) we use a lot to access variables from other scopes. It is a way for you to apply some design patterns such as strategy and dependency inversion .. roughly speaking: call a function, within another function, which reuses values of the first function, in a reduced context ...

Most of the people do not understand event-oriented programming and therefore complain unfairly of javascript.

However, I recommend you take a look here: link

The examples are in javascript but the concept transcends languages.

    
09.07.2014 / 22:41