> PHP's "closures" require you to write down the free variables in an enclosed function and tell PHP that they exist
Can you give an example? I googled "closure conversion" but didn't understand.
Can you give an example? I googled "closure conversion" but didn't understand.
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);
}
In other languages that have true closures, the anonymous function "closes over" the lexical scope in which it was declared.Besides, doesn't Python work the same way?
If you don't assign to x, the compiler will do the right thing without help.
<?php
$x = "b";
$b = 42;
echo $$x; // equivalent to echo $b;
// Here the compiler can't determine all the variables
// used in the function.
// Has a result, there were two choices:
// - capture the whole environment
// - capture explicitly named variables
function () {
return $$x;
}
Hopefully, nobody uses variable-variables these days, however this is the reason behind the introduction of `use` for closures.The necessity of `use` is, IMHO, ridiculous.