Con questo, è possibile definire la propria funzione di continuazione che subentrerà in caso di errore irreversibile. Questo utilizza register_shutdown_function()
per intercettare l'errore fatale.
Usage:
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();
Se si verifica un errore irreversibile (come un errore di analisi), l'esecuzione dello script continuerà da my_continuation_func()
. Altrimenti, include_catch()
restituisce true
se si è verificato un errore durante l'analisi.
Qualsiasi uscita (come echo 'something';
) da include()
viene considerata come un errore. A meno che non abbia abilitato l'output passando true
come terzo argomento a include_try()
.
Questo codice si occupa automaticamente delle possibili modifiche alla directory di lavoro nella funzione di arresto.
È possibile utilizzarlo per qualsiasi numero di include, ma il secondo errore irreversibile che si verifica non può essere intercettato: l'esecuzione si interromperà.
funzioni da includere:
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]);
}
}
ho bisogno di includere tale file a volte può restituire errore fatale per alcuni host. – SarwarCSE
usa 'require' invece di include. –
"potrebbe restituire un errore fatale per qualche host" - che tipo di fatale? Perché esattamente si verifica? – zerkms