我试图在array_map
匿名函数中调用我的对象的一个方法。到目前为止,我收到了预期的错误:
致命错误:在不在...中的对象上下文中时使用$ this
我知道为什么我会收到这个错误,我只是不知道如何实现我想要的...有人有任何建议吗?
这是我目前的代码:
// Loop through the data and ensure the numbers are formatted correctly
array_map(function($value){
return $this->some_method($value,'value',false);
},$this->mssql->data[0]['results'][0]);
答案 0 :(得分:6)
您可以使用“use”关键字
告诉函数“关闭”$ this变量$host = $this;
array_map(function($value) use ($host) {
return $host->some_method($value,'value',false);
},$this->mssql->data[0]['results'][0]);
答案 1 :(得分:0)
此外,您可以从类上下文调用您的地图功能,您不会收到任何错误。像:
class A {
public $mssql = array(
'some output'
);
public function method()
{
array_map(function($value){
return $this->mapMethod($value,'value',false);
},$this->mssql);
}
public function mapMethod($value)
{
// your map callback here
echo $value;
}
}
$a = new A();
$a->method();