0

Today I received the following php error:

Fatal error: Using $this when not in object context.

Pretty straight forward. I was trying to access an object not in scope.

Code sample:

class foo{
function bar(){ 
    array_walk($this->array, 
            function (&$v, $k) {
                if('something'){
                    # code goes here...
                }else{
                    $this->erorr_message = 'Fail'; // breaks in v5.3
                }
            }
        );
     if($this->error_message==''){
             //do something
         }
  }

}

What I learned is that this does not work in 5.3 but it does work in 5.5. Can you show me the PHP update that made this change or explain to me why the scope did not always allow for this to be possible? I think I understand the what just not the why.

Cactus
  • 27,075
  • 9
  • 69
  • 149
Carter
  • 332
  • 3
  • 13

1 Answers1

0

Its right on the man page for php anonymous functions:

Changelog

Version     Description
5.4.0   $this can be used in anonymous functions.
5.3.0   Anonymous functions become available.

http://php.net/manual/en/functions.anonymous.php

Also

PHP 5.4 - 'closure $this support'

Community
  • 1
  • 1
chiliNUT
  • 18,989
  • 14
  • 66
  • 106