关于php:全局变量处理

Global variable handling

当我尝试处理警告消息时,我在全局变量/数组上出错(在最后的print_r行上):

Notice: Undefined variable: errors in........

我也试图在函数之外声明$ errors,但是存在相同的问题。

谢谢

我的代码:

1
2
3
4
5
6
7
8
9
set_error_handler('validation_error_handler', E_WARNING);

function validation_error_handler($error_no, $error_message)
{
    global $errors;
    $errors[] = $error_message;
}

echo '[cc lang="php"]'; print_r($errors); echo '

';


您需要首先将$errors声明为数组:

1
2
set_error_handler('validation_error_handler', E_WARNING);
$errors = array(); // Add this...

更新:

1
2
3
4
5
6
7
8
9
10
11
12
13
set_error_handler('validation_error_handler', E_WARNING);

$errors = array();

function validation_error_handler($error_no, $error_message)
{
    global $errors;
    $errors[] = $error_message;
}

echo preg_match();

echo '[cc lang="php"]'; print_r($errors); echo '

';

这将打印

1
2
3
4
[cc lang="php"]Array
(
    [0] => preg_match() expects at least 2 parameters, 0 given
)

print_r($errors);之前,请确保发生错误/警告


在函数外声明$errors,然后通过引用将其传递到函数中。

1
2
3
4
5
6
7
8
$errors = array();

function validation_error_handler($error_no, $error_message, &$errors)
{
    $errors[] = $error_message;
}

echo '[cc lang="php"]'; print_r($errors); echo '

';

避免以这种方式使用全局变量,因为如果它们包含在其他文件中,则它们可能导致冲突。

另外,请阅读php中的变量范围:http://php.net/manual/en/language.variables.scope.php