[英]php 5.3 access $this->method from Closure
How to access method from closure with PHP 5.3? 如何使用PHP 5.3从闭包访问方法? The code below could run on PHP 5.4 without a problem:
下面的代码可以在PHP 5.4上运行而不会出现问题:
class ClassName
{
function test(Closure $func)
{
$arr = array('name' => 'tim');
foreach ($arr as $key => $value) {
$func($key, $value);
}
}
function testClosure()
{
$this->test(function($key, $value){
//Fatal error: Using $this when not in object context
$this->echoKey($key, $value); // not working on php 5.3
});
}
function echoKey($key, $v)
{
echo $key.' '.$v.'<br/>';
}
}
$cls = new ClassName();
$cls->testClosure();
You need to add object in the closure with "use", but using an "alias" because $this cannot be injected in a closure. 您需要使用“ use”在闭包中添加对象,但要使用“别名”,因为$ this不能注入闭包中。
$object = $this;
$this->test(function($key, $value)use($object){
$object->echoKey($key, $value); // not working on php 5.3
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.