为什么不在匿名函数中设置此全局变量?

时间:2011-02-26 16:47:52

标签: php global-variables 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"

触发匿名功能,我百分百肯定。为什么GLOBALS值没有改变?

1 个答案:

答案 0 :(得分:3)

不确定您在特定函数中执行的操作是否触发了错误,但使用了以下代码:

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


我得到以下输出:

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


这表明:

  • 处理程序函数实际上称为
  • 全局变量受到影响。

(我使用的是PHP 5.3.2)