闭包参数和“use"关键字有什么区别? [英] What's the difference between closure parameters and the 'use' keyword?

查看:25
本文介绍了闭包参数和“use"关键字有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我很困惑,我似乎无法找到这个问题的答案.一个清晰而简单的澄清会很好.

This has got me very confused and I can't seem to find an answer to this question. A clear and simple clarification would be nice.

推荐答案

闭包是在自己的环境中计算的函数,它具有一个或多个在调用函数时可以访问的绑定变量.它们来自函数式编程世界,其中有许多概念在起作用.闭包类似于 lambda 函数,但在某种意义上更智能,因为它们能够与定义闭包的外部环境中的变量进行交互.

A closure is a function that is evaluated in its own environment, which has one or more bound variables that can be accessed when the function is called. They come from the functional programming world, where there are a number of concepts in play. Closures are like lambda functions, but smarter in the sense that they have the ability to interact with variables from the outside environment of where the closure is defined.

use() 关键字让您从函数环境外部、函数内部导入变量.要从外部环境导入的变量在闭包函数定义的 use 子句中指定.默认情况下,它们按值传递.因此,假设该函数没有参数,但您不希望它使用您已有的变量.

The use() keyword let's you import variables from outside the function environment, inside the function. Variables to be imported from the outside environment are specified in the use clause of the closure function definition. By default, they are passed by value. So let's say the function has no parameters, but you wan't it to use a variable you already have.

$string = "Hello World!";
$closure = function() use ($string) { echo $string; };

当您需要创建一个必须在其他地方用作回调并且只能具有定义参数的函数时,这很有用.use() 关键字让您可以使用除作为函数参数传递的变量之外的其他变量.例如在 php.net 示例中:http://php.net/manual/en/函数.anonymous.php

This is useful when you need to create a function what must be used as callback somewhere else, and can only have defined parameters. The use() keyword let's you use other variables in addition to the ones you pass as function arguements. For example on the php.net example: http://php.net/manual/en/functions.anonymous.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);
    }

$callback 必须只有两个参数,因为 array_walk 只允许这么多:

$callback must only have two parameters, because array_walk will only allow that much:

通常,funcname 接受两个参数.数组参数值是第一个,键/索引是第二个.

Typically, funcname takes on two parameters. The array parameter's value being the first, and the key/index second.

那我们能做什么?我们调用 use() 来添加其他变量,这些变量不是 $callback 的范围,而是在它被调用的环境范围内.

So what can we do? We call use() to add other variables that are not the $callback's scope, but in scope of the environment it is being called in.

这篇关于闭包参数和“use"关键字有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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