PHP Closures scoping of variables

后端 未结 3 1202
没有蜡笔的小新
没有蜡笔的小新 2021-01-18 16:15

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:

3条回答
  •  醉梦人生
    2021-01-18 16:34

    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"
    

提交回复
热议问题