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

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

问题描述

可能的重复:
在 PHP 5.3.0 中什么是函数使用"?标识符 ?一个理智的程序员应该使用它吗?

我一直在研究 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);
    }

有人请解释一下这段代码中use的用法.

And somebody please give me an explanation about the usage of use in this code.

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

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

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天全站免登陆