In PHP, what is a closure and why does it use the quot;usequot; identifier?(在 PHP 中,什么是闭包以及为什么它使用“use?标识符?)
问题描述
我正在检查一些 PHP 5.3.0 功能并在网站上遇到了一些看起来很有趣的代码:
I'm checking out some PHP 5.3.0 features and ran across some code on the site that looks quite funny:
public function getTotal($tax)
{
$total = 0.00;
$callback =
/* This line here: */
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);
}
作为匿名函数的示例之一.
有人知道吗?任何文件?而且它看起来很邪恶,应该使用它吗?
Does anybody know about this? Any documentation? And it looks evil, should it ever be used?
推荐答案
这就是 PHP 如何表达一个 关闭.这根本不是邪恶的,事实上它非常强大和有用.
This is how PHP expresses a closure. This is not evil at all and in fact it is quite powerful and useful.
这基本上意味着您允许匿名函数在外部捕获"局部变量(在本例中为 $tax 和对 $total 的引用)它的作用域并保留它们的值(或者在 $total 的情况下是对 $total 本身的引用)作为匿名函数本身的状态.
Basically what this means is that you are allowing the anonymous function to "capture" local variables (in this case, $tax and a reference to $total) outside of it scope and preserve their values (or in the case of $total the reference to $total itself) as state within the anonymous function itself.
这篇关于在 PHP 中,什么是闭包以及为什么它使用“use"?标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 PHP 中,什么是闭包以及为什么它使用“use"?标识符?
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
