Search code examples
phpclassobjectscopearray-map

Call class method from inside array_map anonymous function


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

Solution

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