4

我正在尝试从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]);
4

2 回答 2

6

您可以使用“use”关键字告诉函数“关闭”$this 变量

$host = $this;
array_map(function($value) use ($host) {
    return $host->some_method($value,'value',false);
},$this->mssql->data[0]['results'][0]);
于 2013-10-11T11:10:52.237 回答
0

此外,您可以从类上下文中调用 map 函数,并且不会收到任何错误。喜欢:

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();
于 2013-10-11T11:21:08.283 回答