我有一个只能通过ajax访问的php文件。 ajax调用只需要格式化为json_encode
d输出的数据。我正在尝试创建一个捕获php错误的自定义错误处理函数,而不是直接输出它们,而是将它们传递给它们为json解析器编码的数组。
到目前为止我已经
了// error handler function
function handleErrors($errno, $errstr, $errfile, $errline)
{
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting
return;
}
$response['php_error'][] = "Error [$errno] - $errstr on line $errline in file $errfile";
/* Don't execute PHP internal error handler */
return true;
}
set_error_handler("handleErrors");
//do other stuff that might trigger php errors
if ($result===true){
$response['success'] = true;
}else{
$response['success'] = false;
$response['error'] = $result;
$response['request'] = json_encode($_REQUEST);
}
echo json_encode($response);
我的问题是$response
数组超出了文档其余部分的访问范围,因此它将在json对象中输出。有没有办法通过引用将变量传递给自定义函数或我忽略的另一种方式?
答案 0 :(得分:1)
在您的函数中将$ response定义为全局
function handleErrors($errno, $errstr, $errfile, $errline)
{
global $response;
//further code..
}
或使用$ GLOBALS
$GLOBALS['response']['php_error'][] = "Error [$errno] - $errstr on line $errline in file $errfile";
答案 1 :(得分:1)
在OOP上下文中,您可以将$response
定义为属性。
class myclass {
var $response;
function __construct()
{
set_error_handler(array($this, 'handleErrors'));
}
function handleErrors($errno, $errstr, $errfile, $errline)
{
if ( ! (error_reporting() & $errno))
{
// This error code is not included in error_reporting
return;
}
$this->response['php_error'][] = "Error [$errno] - $errstr on line $errline in file $errfile";
/* Don't execute PHP internal error handler */
return true;
}
function outputAjax()
{
// my code
if ($result === true)
{
$this->response['success'] = true;
} else
{
$this->response['success'] = false;
$this->response['error'] = $result;
$this->response['request'] = json_encode($_REQUEST);
}
echo json_encode($this->response);
}
}