Call class method from inside array_map anonymous

2019-06-24 06:03发布

I am trying to call one of my object's methods from within an array_map anonymous function. So far I am receiving the expected error of:

Fatal error: Using $this when not in object context in...

I know why I am getting this error, I just don't know a way to achieve what I am trying to... Does anybody have any suggestions?

Here is my current code:

// 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]);

2条回答
甜甜的少女心
2楼-- · 2019-06-24 06:43

Also, you can call your map function from a class context and you will not receive any errors. Like:

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();
查看更多
女痞
3楼-- · 2019-06-24 06:49

You can tell the function to "close over" the $this variable by using the "use" keyword

$host = $this;
array_map(function($value) use ($host) {
    return $host->some_method($value,'value',false);
},$this->mssql->data[0]['results'][0]);
查看更多
登录 后发表回答