ฟังก์ชัน set_exception_handler

ฟังก์ชัน set_exception_handler อนุญาตให้กำหนดฟังก์ชันที่จะถูกเรียกเพื่อจัดการข้อยกเว้นที่ไม่ได้จับ ในพารามิเตอร์จะส่งชื่อฟังก์ชันตัวจัดการหรือฟังก์ชันแบบไม่ระบุชื่อ ตัวจัดการจะได้รับออบเจ็กต์ข้อยกเว้นเป็นพารามิเตอร์

ไวยากรณ์

phpset_exception_handler(callable $exception_handler): callable

ตัวอย่าง

มาตั้งตัวจัดการข้อยกเว้นง่ายๆ:

php<?php
  function myExceptionHandler($exception) {
    echo 'Caught exception: ' . $exception->getMessage();
  }
  
  set_exception_handler('myExceptionHandler');
  
  throw new Exception('Something went wrong!');
?>

ผลลัพธ์การทำงานของโค้ด:

php'Caught exception: Something went wrong!'

ตัวอย่าง

การใช้ฟังก์ชันแบบไม่ระบุชื่อเป็นตัวจัดการ:

php<?php
  set_exception_handler(function($exception) {
    echo 'Error: ' . $exception->getMessage();
  });
  
  throw new Exception('Critical error');
?>

ผลลัพธ์การทำงานของโค้ด:

php'Error: Critical error'

ตัวอย่าง

การกู้คืนตัวจัดการก่อนหน้า:

php<?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(); // กู้คืน firstHandler
  
  throw new Exception('Test');
?>

ผลลัพธ์การทำงานของโค้ด:

php'First handler: Test'