在 PHP 中,什么是闭包以及为什么它使用“use"?标识符?

2022-01-30 00:00:00 closures php

我正在检查一些 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.

相关文章