在函数中使用关键字 - PHP [英] Use keyword in functions - PHP

查看:99
本文介绍了在函数中使用关键字 - PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在Php 5.3.0中,功能使用标识符?

我一直在研究Closures PHP,这是我关注的:

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)

当我搜索时使用在PHP中,它找到使用关键字,它在命名空间中使用,但在这里它看起来不同。

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

推荐答案

use在这种情况下的使用是正确的。

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

对于闭包,要访问函数上下文之外的变量,需要使用use函数显式授予对函数的权限。在这种情况下,它意味着你授予函数访问$ tax和$ total变量。

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.

你会注意到$ tax是作为一个getTotal函数的参数,而$ total设置在定义闭包的行的上面。

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.

另一件要指出的是$ tax作为副本传递$ total通过引用传递(通过在前面附加&符号)。通过引用传递允许闭包修改变量的值。在这种情况下,$ tax的值的任何更改只会在闭包内有效,而$ total的实际值。

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.

这篇关于在函数中使用关键字 - PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆