我想获得以下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();
// OUTPUT:
none
//预期输出:
HELLO
HELLO
HELLO
HELLO
注意:我想要一个解决方案,当静态方法变为非静态时也可以使用,否则这两种情况的两种不同解决方案都可以。
答案 0 :(得分:0)
答案是使用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