1

I found code like this and can't find what it does

$callback = function ($pricePerItem) use ($tax, &$total) {
    $total += $pricePerItem * ($tax + 1.0);
};

php documentation only say

The 'use' keyword also applies to closure constructs:

but no explanation what it actually does.

jcubic
  • 61,973
  • 54
  • 229
  • 402
  • 1
    possible duplicate of [In Php 5.3.0 what is the Function "Use" Identifier ? Should a sane programmer use it?](http://stackoverflow.com/questions/1065188/in-php-5-3-0-what-is-the-function-use-identifier-should-a-sane-programmer-us) – Felix Kling May 07 '12 at 08:00

2 Answers2

3

It controls the scope. In this case, the variables $tax and $total are declared outside of the anonymous function. Because they are listed in the use-clause, they are accessible from within.

The ampersand makes the variable fully shared - e.g. changes made within the closure will reflect in the outer scope. In the case of $tax, the variable is a copy, so can't be changed from within the closure.

Most other languages with support for anonymous functions would just per default have lexical scope, but since PHP already have other scoping rules, this would create all sorts of weird situations, breaking backwards compatibility. As a resort, this - rather awkward - solution was put in place.

troelskn
  • 115,121
  • 27
  • 131
  • 155
1

Check this - http://php.net/manual/en/functions.anonymous.php, if an anonymous function wants to use local variables (for your code, it's $tax and $total), it should use use to reference them.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Tom
  • 4,612
  • 4
  • 32
  • 43