在闭包中使用外部变量的方法是使用use关键字。
PHP使用闭包(Closure)来实现匿名函数, 匿名函数最强大的功能也就在匿名函数所提供的一些动态特性以及闭包效果, 匿名函数在定义的时候如果需要使用作用域外的变量需要使用如下的语法来实现:
<?php
$name = 'TIPI Team';
$func = function() use($name) {
echo "Hello, $name";
}
$func(); // Hello TIPI Team
在类方法中将$this传入到闭包中:
class Foo
{
public function bar()
{
$that = &$this;
return function() use(&$that)
{
print_r($that);
};
}
}