4

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
  • Upgrade to PHP 5.4, which added support for $this in closures. Commented Oct 11, 2013 at 12:13

2 Answers 2

6

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

You do not need to pass objects by reference like &$object, because objects are already passed by reference.
0

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

2 Comments

This is exactly what I am doing!
Hmmm, i'm not so sure that your code look exactly the same, because you sould not receive that error if you do so, and i'm pretty sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.