【问题标题】:How do I pass multiple arguments to an anonymous function in PHP?如何将多个参数传递给 PHP 中的匿名函数?
【发布时间】:2017-02-22 21:47:16
【问题描述】:

PHP 5.3+ 支持anonymous functions(尽管在绑定方面,它在 PHP 7.x+ 中对它们的支持略有不同)。我正在运行 PHP 5.6.x

是否有一种语法允许将多个参数传递给匿名函数(而不是仅使用数组)用作回调 。这些示例中的哪些(如果有)在 PHP 中是可能的?

示例 1

function ($str1, $str2 ){   //But, that would be too easy, right?
    return $str1 . $str2;
}

示例 2

function () use ($string, $min, $max) {  // Not seeing this in the manual.
    $length = mb_strlen($string, 'UTF-8');
    return ($length >= $min) && ($length <= $max);
}

示例 3

只是出于好奇,这种形式可能吗?

function ($str1, $str2 ) use ($int1, $int2) { // But, that would be in the manual?
    return $str1 . $str2 .' '. $int2 + $int2;
}

我查看了 PHP 手册,但没有看到我要查找的内容。

【问题讨论】:

  • 三种形式都可以;但是标准参数是在调用函数的地方传递的;在定义闭包时“使用”参数
  • 在 PHP 5.6 中,您还可以通过 ... 运算符使用参数打包/解包:function (...$args){ return implode($args); }
  • @MarkBaker 您对use 参数的解释应该在PHP 手册中。我现在更好地理解了这一点。谢谢你。我了解了 JavaScript 中的匿名函数和闭包……我并不想做一个完全平行的事情。我的意思是说,当您说“定义闭包的位置”时,我理解。很棒。
  • @MarkBaker 谢谢。我将不得不查找参数打包/拆包。干杯。

标签: php callback anonymous-function


【解决方案1】:

示例 2 适合我。

function () use ($string, $min, $max) {  // Not seeing this in the manual.
    $length = mb_strlen($string, 'UTF-8');
    return ($length >= $min) && ($length <= $max);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 2019-11-23
    • 2011-05-11
    • 1970-01-01
    相关资源
    最近更新 更多