Với điều này, bạn có thể xác định chức năng tiếp tục của riêng bạn sẽ tiếp quản trong trường hợp có lỗi nghiêm trọng. Điều này sử dụng register_shutdown_function()
để chặn lỗi nghiêm trọng.
Cách sử dụng:
function my_continuation_func($filename, $arg2) {
// On fatal error during include, continue script execution from here.
// When this function ends, or if another fatal error occurs,
// the execution will stop.
}
include_try('my_continuation_func', array($filename, $arg2));
$data = include($filename);
$error = include_catch();
Nếu một lỗi nghiêm trọng xảy ra (như một lỗi phân tích cú pháp), thực hiện kịch bản sẽ tiếp tục từ my_continuation_func()
. Nếu không, include_catch()
trả về true
nếu có lỗi trong khi phân tích cú pháp.
Mọi đầu ra (như echo 'something';
) từ include()
được coi là lỗi. Trừ khi bạn đã bật đầu ra bằng cách chuyển true
làm đối số thứ ba cho include_try()
.
Mã này sẽ tự động xử lý các thay đổi thư mục hoạt động có thể có trong chức năng tắt máy.
Bạn có thể sử dụng điều này cho bất kỳ số lượng bao gồm, nhưng lỗi nghiêm trọng thứ hai xảy ra không thể bị chặn: việc thực hiện sẽ dừng lại.
Chức năng để được bao gồm:
function include_try($cont_func, $cont_param_arr, $output = false) {
// Setup shutdown function:
static $run = 0;
if($run++ === 0) register_shutdown_function('include_shutdown_handler');
// If output is not allowed, capture it:
if(!$output) ob_start();
// Reset error_get_last():
@user_error('error_get_last mark');
// Enable shutdown handler and store parameters:
$params = array($cont_func, $cont_param_arr, $output, getcwd())
$GLOBALS['_include_shutdown_handler'] = $params;
}
function include_catch() {
$error_get_last = error_get_last();
$output = $GLOBALS['_include_shutdown_handler'][2];
// Disable shutdown handler:
$GLOBALS['_include_shutdown_handler'] = NULL;
// Check unauthorized outputs or if an error occured:
return ($output ? false : ob_get_clean() !== '')
|| $error_get_last['message'] !== 'error_get_last mark';
}
function include_shutdown_handler() {
$func = $GLOBALS['_include_shutdown_handler'];
if($func !== NULL) {
// Cleanup:
include_catch();
// Fix potentially wrong working directory:
chdir($func[3]);
// Call continuation function:
call_user_func_array($func[0], $func[1]);
}
}
Tôi cần phải bao gồm tập tin mà đôi khi nó có thể trở lại lỗi nghiêm trọng đối với một số máy chủ. – SarwarCSE
sử dụng 'require' thay vì bao gồm. –
"nó có thể trả về lỗi nghiêm trọng cho một số máy chủ" - loại tử vong nào? Tại sao chính xác nó xảy ra? – zerkms