Class method call from inside anonymous array_map function

I am trying to call one of my object methods from an anonymous function array_map. While I get the expected error:

Fatal error: using $ this if not in the context of an object in ...

I know why I get this error, I just don’t know how to get what I'm trying to ... Does anyone 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]);
+4
source share
2 answers

You can tell the function to "close" this $ variable 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]);
+5
source

, , . :

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

All Articles