What is the benefit and in what cases use closures in PHP?

Asked

Viewed 365 times

4

Ex.: 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);
}

http://www.php.net/manual/en/class.closure.php

  • I really like using Closures in PHP 5.4, because it has a very useful method called bindTo()

1 answer

8


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 us to be event-oriented (like c#) we use a lot to access variables from other scopes. It’s a way for you to apply some Patterns design like Strategy and dependency inversion.. roughly speaking: calling a function, within another function, that reuses values from the first function, in a reduced context...

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

However, I recommend you take a look here: http://howtonode.org/why-use-closure

The examples are in javascript but the concept transcends languages.

  • I thought it was something more complex, but it really became clear.

  • I use a lot! I was very happy when I got to know Action and Func do c# and saw that I could maintain the style of javascript programming! Whereas style in javascript depends on one’s experience...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.