5

I am looking at the PHP example of Closures on http://us1.php.net/manual/en/functions.anonymous.php

It provides the example code below and states:

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:

I am confused as to how this is working though. $quantity and $product variables do not seem to me that they would be available inside the Closure function. Wouldn't the Parent Scope be 1 scope up in this case the getTotal() function?

enter image description here

JasonDavis
  • 48,204
  • 100
  • 318
  • 537
  • Seems a lot like this question: [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) – Marty McVry Sep 04 '13 at 18:35
  • 1
    Look up the documentation for array walk ... this is where those parameters are getting pushing into the function. – Orangepill Sep 04 '13 at 18:35

3 Answers3

12

You're misunderstanding the function signature. $quantity and $product are the regular arguments that will be passed into the function when it's called, they indeed do not exist in the parent scope and aren't meant to. use ($tax, &$total) are the closed over variables from the parent scope.

$foo = 'foo';             // closed over variable
                          // vvvv
$func = function ($bar) use ($foo) {
               // ^^^^
               // regular function argument

    return $foo . $bar;
};

echo $func('baz');  // "foobaz"
deceze
  • 510,633
  • 85
  • 743
  • 889
2

The closure arguments $quantity and $product do not exist per se in the function definition, they are just placeholders that array_walk will fill with real values during its execution procedure. The use arguments are extra variables that you import into the array_walk call's scope that otherwise would not be available to the function.

silkfire
  • 24,585
  • 15
  • 82
  • 105
0

The two variable is question are what get passed into the callback by array_walk.

The first parameter will be passed as the value of each of the elements in the array, the second will be the key of the array.

The closed over variables are the ones referenced in the use clause.

Orangepill
  • 24,500
  • 3
  • 42
  • 63