$that = $this;
$closure = function (...) use ($that) { ... };
发现在:http://css.dzone.com/polls/what-new-feature-php-54
请问有人能解释一下它的作用吗?最好附带一个例子。
$that = $this;
$closure = function (...) use ($that) { ... };
发现在:http://css.dzone.com/polls/what-new-feature-php-54
请问有人能解释一下它的作用吗?最好附带一个例子。
这是一种从匿名函数中访问所在类的方法的方法。但由于标题是“php 5.4闭包”,您不再需要这样做,这是5.4中进行的更新之一,您可以使用$ this(无需将其传递给另一个变量如$ that)。您可以在http://php.net/ChangeLog-5.php 这里看到其中一个更改是“增加了闭包$this支持”。
闭包是一个匿名函数,通常与回调一起使用。例如:
my_function_with_callback('some-parameter', function() {
//Do stuff here
});
重新绑定意味着您可以在匿名函数中使用$this,而无需使用'use($var)',因此当您在类中时:
class MyClass {
public function myMethod() {
$anon = function() {
//$this still refers to MyClass here
};
}
}
$this
/$that
还是匿名函数? - deceze