randomguy
randomguy

Reputation: 12252

Why isn't this global variable set inside an anonymous function?

$GLOBALS['failed'] = "no";

set_error_handler(function($errno, $errstr) {
    $GLOBALS['failed'] = "yes";
});

a_function_that_triggers_the_above_function();

echo $GLOBALS['failed']."\n"; # => "no"

That anonymous function is triggered, I'm 100% sure. Why isn't the GLOBALS value changed?

Upvotes: 1

Views: 540

Answers (1)

Pascal MARTIN
Pascal MARTIN

Reputation: 401142

Not sure what you are doing in your specific function that triggers an error, but using this portion of code :

$GLOBALS['failed'] = "no";

set_error_handler(function($errno, $errstr) {
    var_dump('handler !');
    var_dump($errstr);
    $GLOBALS['failed'] = "yes";
});

echo 10 / 0;

var_dump($GLOBALS['failed']);


I get the following output :

string 'handler !' (length=9)
string 'Division by zero' (length=16)
string 'yes' (length=3)


Which shows that :

  • The handler function is actually called
  • The global variable is affected.

(I'm using PHP 5.3.2)

Upvotes: 3

Related Questions