Use keyword in functions

Possible Duplicate:
In Php 5.3.0 what is the Function “Use” Identifier ? Should a sane programmer use it?

I've been examining the Closures in PHP and this is what took 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 somebody please give me an explanation about the usage of use in this code.

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

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

Thanks.


The use of "use" is correct in this case too.

With closures, to access variables that are outside of the context of the function you need to explicitly grant permission to the function using the use function. What it means in this case is that you're granting the function access to the $tax and $total variables.

You'll noticed that $tax was passed as a parameter of the getTotal function while $total was set just above the line where the closure is defined.

Another thing to point out is that $tax is passed as a copy while $total is passed by reference (by appending the & sign in front). Passing by reference allows the closure to modify the value of the variable. Any changes to the value of $tax in this case will only be effective within the closure while the real value of $total.


When you declare an anonymous function in PHP you need to tell it which variables from surrounding scopes (if any) it should close over — they don't automatically close over any in-scope lexical variables that are mentioned in the function body. The list after use is simply the list of variables to close over.


这意味着你的内部函数可以使用来自外部函数的变量$ tax和$ total,而不仅仅是它的参数。

链接地址: http://www.djcxy.com/p/10140.html

上一篇: 这个foreach循环负责上帝杀死猫吗?

下一篇: 在功能中使用关键字