Question

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]);
Was it helpful?

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

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top