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?
A closure is an anonymous function that can access variables imported from the outside scope without using any global variables. Theoretically, a closure is a function with some arguments closed (e.g. fixed) by the environment when it is defined. Closures can work around variable scope restrictions in a clean way.
Basically a closure in PHP is a function that can be created without a specified name - an anonymous function. Here's a closure function created as the second parameter of array_walk() . By specifying the $v parameter as a reference one can modify each value in the original array through the closure function.
Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.
A Closure is an anonymous function. Closures are often used as callback methods and can be used as a parameter in a function. If you take the following example: function handle(Closure $closure) { $closure(); } handle(function(){ echo 'Hello! '; });
A simpler answer.
function ($quantity) use ($tax, &$total) { .. };
$tax
inside the closure has no external effect, unless it is a pointer, like an object is.&$total
. This way, modifying the value of $total
DOES HAVE an external effect, the original variable's value changes.As @Mytskine pointed out probably the best in-depth explanation is the RFC for closures. (Upvote him for this.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With