您如何知道要放在闭包中的参数/参数? [英] How do you know what parameters/arguments to put in a closure?

查看:59
本文介绍了您如何知道要放在闭包中的参数/参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

闭包何时具有参数(或带参数的闭包如何工作)?我知道 use()用来 import 匿名函数之外的变量,但是闭包本身的参数呢?

When do closures have parameters (or how do closures with parameters work)? I know that use() is used to import variables outside the anonymous function, but what about the parameter(s) of the closure itself?

推荐答案

带有参数的闭包示例如下:

An example of closures with parameters is currying:

function greeter($greeting)
{
  return function($whom) use ($greeting) {
    // greeting is the closed over variable
    return "$greeting $whom";
  };
}

$hello_greeter = greeter('hello');

echo $hello_greeter('world'); // will print 'hello world';

greeter 函数将返回一个半实现"函数,该函数将始终以相同的问候语开头,随后是传递给它的任何东西(例如,要问候的人).

The greeter function will return a "half-implemented" function that will always start with the same greeting, followed by whatever is passed into it (e.g. the person to greet).

这篇关于您如何知道要放在闭包中的参数/参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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