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 ' |
';
code> pre>
您需要首先将
1 2 |
更新:
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 ' |
';
code> pre>
这将打印
1 2 3 4 |
code> pre>
在函数外声明
1 2 3 4 5 6 7 8 |
';
code> pre>
避免以这种方式使用全局变量,因为如果它们包含在其他文件中,则它们可能导致冲突。
另外,请阅读php中的变量范围:http://php.net/manual/en/language.variables.scope.php