Funktio set_exception_handler
Funktio set_exception_handler mahdollistaa funktion määrittelyn, jota kutsutaan käsittelemään kiinniotettuja poikkeuksia. Parametrina annetaan käsittelijäfunktion nimi tai anonyymi funktio. Käsittelijä saa poikkeusobjektin parametrina.
Syntaksi
set_exception_handler(callable $exception_handler): callable
Esimerkki
Asetetaan yksinkertainen poikkeuskäsittelijä:
<?php
function myExceptionHandler($exception) {
echo 'Caught exception: ' . $exception->getMessage();
}
set_exception_handler('myExceptionHandler');
throw new Exception('Something went wrong!');
?>
Koodin suorituksen tulos:
'Caught exception: Something went wrong!'
Esimerkki
Anonyymin funktion käyttö käsittelijänä:
<?php
set_exception_handler(function($exception) {
echo 'Error: ' . $exception->getMessage();
});
throw new Exception('Critical error');
?>
Koodin suorituksen tulos:
'Error: Critical error'
Esimerkki
Edellisen käsittelijän palauttaminen:
<?php
function firstHandler($exception) {
echo 'First handler: ' . $exception->getMessage();
}
function secondHandler($exception) {
echo 'Second handler: ' . $exception->getMessage();
}
set_exception_handler('firstHandler');
$old_handler = set_exception_handler('secondHandler');
restore_exception_handler(); // Palauttaa firstHandler
throw new Exception('Test');
?>
Koodin suorituksen tulos:
'First handler: Test'