0

我想让以下 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

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

4

1 回答 1

0

答案是使用 PHPuse关键字:

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
于 2015-02-10T17:00:50.040 回答