在 PHP 中,什么是闭包以及为什么使用“use"?标识符? [英] In PHP, what is a closure and why does it use the "use" identifier?

查看:28
本文介绍了在 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"?标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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