在函数中使用关键字 - PHP
我一直在检查 PHP 中的闭包,这引起了我的注意:
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
的用法。
function ($quantity, $product) use ($tax, &$total)
当我在 PHP 中搜索 use
时,它发现 use
关键字在命名空间中使用,但这里看起来不同。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,“使用”的使用也是正确的。
使用闭包,要访问函数上下文之外的变量,您需要使用 use 函数显式授予函数权限。在这种情况下,这意味着您授予函数对 $tax 和 $total 变量的访问权限。
您会注意到 $tax 作为 getTotal 函数的参数传递,而 $total 则设置在定义闭包的行上方。
另一件需要指出的是 $tax 作为副本传递,而 $total 通过引用传递(通过在前面附加 & 符号)。通过引用传递允许闭包修改变量的值。在这种情况下,对 $tax 值的任何更改都只会在闭包内有效,而 $total 的实际值。
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.
当您在 PHP 中声明匿名函数时,您需要告诉它应该关闭周围作用域中的哪些变量(如果有)——它们不会自动关闭函数体中提到的任何作用域内的词法变量。
use
之后的列表只是要关闭的变量列表。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,而不仅仅是其参数。
This means your inner function can use variables $tax and $total from the outer function, not only its parameters.