如何将返回的函数局部变量绑定到方法参数?

How to bind returned function local variable to method parameter?

我想让下面的 PHP 代码工作。不起作用的部分是内部变量 $greetingCount (返回函数的局部变量)没有绑定到外部变量 $greetingCount (方法参数变量)。

class Greetings {

  public static function getRepeatGreeterFunc($greetingCount) {

    $repeatGreeter = function($greeting) {

      // I want $greetingCount to bind to the outer $greetingCount here.
      // If 4 is passed to getRepeatGreeterFunc, then it should be 4 here,
      // so that what I get is a function that prints the greeting 4 times.

      for ($i = 0; $i < $greetingCount; $i++) {

        echo $greeting . "\n";

      }

    };

    return $repeatGreeter;

  }

  public function greet() {

    $repeatGreeter = self::getRepeatGreeterFunc(4);
    call_user_func($repeatGreeter, "HELLO");

  }

}

$greetings = new Greetings();
$greetings->greet();

// 输出:

none

// 预期输出:

HELLO
HELLO
HELLO
HELLO

注意:我想要一个在静态方法变为非静态时也能工作的解决方案,否则这两种情况的两种不同解决方案都可以。

答案是利用PHP use关键字:

class Greetings {

  public static function getRepeatGreeterFunc($greetingCount) {

    $repeatGreeter = function($greeting) use ($greetingCount) {

      // I want $greetingCount to bind to the outer $greetingCount here.
      // If 4 is passed to getRepeatGreeterFunc, then it should be 4 here,
      // so that what I get is a function that prints the greeting 4 times.

      for ($i = 0; $i < $greetingCount; $i++) {

        echo $greeting . "\n";

      }

    };

    return $repeatGreeter;

  }

  public function greet() {

    $repeatGreeter = self::getRepeatGreeterFunc(4);
    call_user_func($repeatGreeter, "HELLO");

  }

}

$greetings = new Greetings();
$greetings->greet();

输出:

HELLO
HELLO
HELLO
HELLO