当前位置:首页 > PHP教程 > php函数 > 列表

register_shutdown_function函数在php中具体应用(含详解)

发布:smiling 来源: PHP粉丝网  添加日期:2022-06-22 08:29:58 浏览: 评论:0 

某些情况下,我们需要在程序执行结束时,做一些后续的处理工作,这个时候,php的register_shutdown_function函数就可以帮我们来实现这个功能。

一 register_shutdown_function函数简介

当PHP程序执行完成后,自动执行register_shutdown_function函数,该函数需要一个参数,用来指定由谁处理这些后续的工作。其中,程序执行完成,分为以下几种情况:

⑴ php代码执行过程中发生错误

⑵ php代码顺利执行成功

⑶ php代码运行超时

⑷ 页面被用户强制停止

二 register_shutdown_function函数的使用步骤

register_shutdown_function函数的使用非常简单,最多2步即可。

1. 自定义一个php类,名字为CustomHandle.php,内如如下:

  1. <?php 
  2.  
  3. namespace com\antp; 
  4.  
  5. class CustomHandle { 
  6.  
  7. public static function systemError() { 
  8.  
  9. $message = ''
  10.  
  11. if ($error = error_get_last()) { 
  12.  
  13. //程序报错处理,通常会跳转到用户自定义的页面,同时记录错误信息 
  14.  
  15. $separator = "\r\n"
  16.  
  17. $message .= "错误:" . $error['message'] . $separator
  18.  
  19. $message .= "文件:" . $error['file'] . $separator
  20.  
  21. $message .= "行数:" . $error['line'] . $separator
  22.  
  23. $message = str_replace($separator'<br />'$message); 
  24.  
  25. header('Location:http://'.$_SERVER['HTTP_HOST'].'/error.php'); 
  26.  
  27. exit
  28.  
  29. }else
  30.  
  31. //此处处理其它一些业务逻辑 
  32.  
  33.  
  34.  

2. 引入注册函数

在程序入口处,引入CustomHandle.php文件,同时,注册register_shutdown_function函数,如下:

require 'CustomHandle.php';

register_shutdown_function(array('com\antp\CustomHandle','systemError'));

此时,不管你的php代码执行是否成功,最后都会CustomHandle类中的systemError方法。

Tags: register_shutdown_function

分享到: