set_exception_handler funksiyası

set_exception_handler funksiyası tutulmamış istisnaları emal etmək üçün çağırılacaq funksiyanı təyin etməyə imkan verir. Parametr kimi emaledicinin funksiya adı və ya anonim funksiya ötürülür. Emaledicı parametr kimi istisna obyektini alır.

Sintaksis

phpset_exception_handler(callable $exception_handler): callable

Nümunə

Sadə bir istisna emaledicisi təyin edək:

php<?php
  function myExceptionHandler($exception) {
    echo 'Tutulan istisna: ' . $exception->getMessage();
  }
  
  set_exception_handler('myExceptionHandler');
  
  throw new Exception('Nəsə düz getmədi!');
?>

Kodun icra nəticəsi:

php'Tutulan istisna: Nəsə düz getmədi!'

Nümunə

Emaledicı kimi anonim funksiyanın istifadəsi:

php<?php
  set_exception_handler(function($exception) {
    echo 'Xəta: ' . $exception->getMessage();
  });
  
  throw new Exception('Kritik xəta');
?>

Kodun icra nəticəsi:

php'Xəta: Kritik xəta'

Nümunə

Əvvəlki emaledicinin bərpası:

php<?php
  function firstHandler($exception) {
    echo 'Birinci emaledicı: ' . $exception->getMessage();
  }
  
  function secondHandler($exception) {
    echo 'İkinci emaledicı: ' . $exception->getMessage();
  }
  
  set_exception_handler('firstHandler');
  $old_handler = set_exception_handler('secondHandler');
  restore_exception_handler(); // Birinci emaledicini bərpa edir
  
  throw new Exception('Test');
?>

Kodun icra nəticəsi:

php'Birinci emaledicı: Test'