您的位置:首页 > 技术中心 > PHP教程 >

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

时间:2022-02-11 13:25

register_shutdown_function在php中的应用(含详解)

某些情况下,我们需要在程序执行结束时,做一些后续的处理工作,这个时候,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,内如如下:

<?php
namespace com\antp;
class CustomHandle {
public static function systemError() {
$message = '';
if ($error = error_get_last()) {
//程序报错处理,通常会跳转到用户自定义的页面,同时记录错误信息
$separator = "\r\n";
$message .= "错误:" . $error['message'] . $separator;
$message .= "文件:" . $error['file'] . $separator;
$message .= "行数:" . $error['line'] . $separator;
$message = str_replace($separator, '<br />', $message);
header('Location:http://'.$_SERVER['HTTP_HOST'].'/error.php');
exit;
}else{
//此处处理其它一些业务逻辑
}
}
}

2. 引入注册函数

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

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

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

————————————————

版权声明:本文为CSDN博主「木鱼大叔」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/tdcqfyl/article/details/52291237

推荐教程:《PHP教程》

以上就是register_shutdown_function函数在php中具体应用(含详解)的详细内容,更多请关注gxlsystem其它相关文章!

本类排行

今日推荐

热门手游