Reputation: 165
How to access method from closure with PHP 5.3? The code below could run on PHP 5.4 without a problem:
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();
Upvotes: 0
Views: 163
Reputation: 684
You need to add object in the closure with "use", but using an "alias" because $this cannot be injected in a closure.
$object = $this;
$this->test(function($key, $value)use($object){
$object->echoKey($key, $value); // not working on php 5.3
});
Upvotes: 3