在函数中使用关键字 - PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6320521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use keyword in functions - PHP
提问by Tarik
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:
我一直在检查 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);
}
And somebody please give me an explanation about the usage of use
in this code.
有人请给我解释一下use
这段代码中的用法。
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.
当我use
在 PHP 中搜索时,它use
会在命名空间中找到关键字,但在这里它看起来不同。
Thanks.
谢谢。
回答by Francois Deschenes
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.
使用闭包,要访问函数上下文之外的变量,您需要使用 use 函数显式授予函数权限。在这种情况下,这意味着您授予函数访问 $tax 和 $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 作为 getTotal 函数的参数传递,而 $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.
需要指出的另一件事是 $tax 作为副本传递,而 $total 通过引用传递(通过在前面附加 & 符号)。通过引用传递允许闭包修改变量的值。在这种情况下,对 $tax 值的任何更改仅在闭包内有效,而 $total 的实际值。
回答by hobbs
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.
当你在 PHP 中声明一个匿名函数时,你需要告诉它应该关闭周围范围内的哪些变量(如果有的话)——它们不会自动关闭函数体中提到的任何范围内的词法变量。后面use
的列表只是要关闭的变量列表。
回答by Yuri Stuken
This means your inner function can use variables $tax and $total from the outer function, not only its parameters.
这意味着您的内部函数可以使用外部函数中的变量 $tax 和 $total,而不仅仅是其参数。