Use keyword in functions - PHP

Possible duplicate:
In Php 5.3.0, what is the "Use" identifier function? Should a system programmer use it?

I studied Closures in PHP, and that is what caught my attention:

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

And someone, please give me an explanation about using use in this code.

 function ($quantity, $product) use ($tax, &$total) 

When I look at use in PHP, it finds the use keyword, where it is used in namespaces, but here it looks different.

Thank.

+70
closures php anonymous-function
Jun 12 '11 at 6:25
source share
3 answers

The use of "use" is also true in this case.

With closure to access variables that are outside the context of the function, you need to explicitly grant the function permission using the use function. In this case, this means that you give the function access to the variables $ tax and $ total.

You noticed that $ tax was passed as a parameter to the getTotal function, and $ total was set just above the line where the closure is defined.

Another thing indicating that $ tax is passed as a copy, while $ total is passed by reference (by adding and entering from the front). Passing by reference allows closure to change the value of a variable. Any changes in the value of $ tax in this case will be effective only in closing, while the real value of $ total.

+103
Jun 12 2018-11-12T00:
source share
— -

When you declare an anonymous function in PHP, you need to say which variables from the surrounding areas (if any) should be closed - they do not automatically close by any of the lexical variables in the area that are mentioned in the function body, the list after use is just list of variables to close.

+14
Jun 12 2018-11-12T00:
source share

This means that your inner function can use the $ tax and $ total variables from the outer function, and not just its parameters.

+2
Jun 12 '11 at 6:30 a.m.
source share



All Articles