在PHP 5.3.0中,什么是函数“use”标识符? [英] In PHP 5.3.0, what is the function "use" identifier?

查看:129
本文介绍了在PHP 5.3.0中,什么是函数“use”标识符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了一些 PHP 5.3.0 功能,并在网站上看起来很有趣的一些代码上运行:

  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);
}

作为匿名函数



有人知道吗?任何文档?

这是PHP如何表达一个关闭。这不是邪恶的,事实上它是相当强大和有用的。



基本上这意味着你允许匿名函数捕获局部变量(在这种情况下, $ tax 并引用 $ total ),并保留其值(或在 $ total 引用 $ total 本身)作为匿名函数本身内的状态。


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);
}

as one of the examples on anonymous functions.

Does anybody know about this? Any documentation? And it looks evil, should it ever be used?

解决方案

This is how PHP expresses a closure. This is not evil at all and in fact it is quite powerful and useful.

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 5.3.0中,什么是函数“use”标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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