Call class method from inside array_map anonymous function

蓝咒 提交于 2019-12-10 17:19:08

问题


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

回答1:


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



回答2:


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();


来源:https://stackoverflow.com/questions/19316623/call-class-method-from-inside-array-map-anonymous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!