search
HomeBackend DevelopmentPHP TutorialDetailed introduction of register_shutdown_function function

在PHP核心技术与最佳实践中,提及了一个函数register_shutdown_function,我发现这个函数非常的有意思,今天就来给大家详细解析一下这个函数

1. 函数说明

定义:该函数是来注册一个会在PHP中止时执行的函数

参数说明:

void register_shutdown_function ( callable $callback [, mixed $parameter [, mixed $... ]] )


注册一个 callback ,它会在脚本执行完成或者 exit() 后被调用。

callback:待注册的中止回调

parameter:可以通过传入额外的参数来将参数传给中止函数

2. PHP中止的情况

PHP中止的情况有三种:

执行完成

exit/die导致的中止

发生致命错误中止

a. 第一种情况,执行完成

<?php
function test()
{
 echo &#39;这个是中止方法test的输出&#39;;
}
register_shutdown_function(&#39;test&#39;);
echo &#39;before&#39; . PHP_EOL;


运行:

before

这个是中止方法test的输出


注意:输出的顺序,等执行完成了之后才会去执行register_shutdown_function的中止方法test

b. 第二种情况,exit/die导致的中止

<?php
function test()
{
 echo &#39;这个是中止方法test的输出&#39;;
}
  
register_shutdown_function(&#39;test&#39;);
  
echo &#39;before&#39; . PHP_EOL;
exit();
echo &#39;after&#39; . PHP_EOL;


运行:

before

这个是中止方法test的输出


后面的after并没有输出,即exit或者是die方法导致提前中止。

c. 第三种情况,发送致命错误中止

<?php
function test()
{
 echo &#39;这个是中止方法test的输出&#39;;
}
  
register_shutdown_function(&#39;test&#39;);
  
echo &#39;before&#39; . PHP_EOL;
  
// 这里会发生致命错误
$a = new a();
  
echo &#39;after&#39; . PHP_EOL;


运行:

before
Fatal error: Uncaught Error: Class &#39;a&#39; not found in D:\laragon\www\php_book\test.php on line 1
Error: Class &#39;a&#39; not found in D:\laragon\www\php_book\test.php on line 12
Call Stack:
 0.0020  360760 1. {main}() D:\laragon\www\php_book\test.php:0

这个是中止方法test的输出


后面的after也是没有输出,致命错误导致提前中止了。

3. 参数

第一个参数支持以数组的形式来调用类中的方法,第二个以及后面的参数都是可以当做额外的参数传给中止方法。

<?php
  
class Shutdown
{
 public function stop()
 {
  echo "这个是stop方法的输出";
 }
}
  
// 当PHP终止的时候(执行完成或者是遇到致命错误中止的时候)会调用new Shutdown的stop方法
register_shutdown_function([new Shutdown(), &#39;stop&#39;]);
  
// 将因为致命错误而中止
$a = new a();
  
// 这一句并没有执行,也没有输出
echo &#39;必须终止&#39;;

   


也可以在类中执行:

<?php
  
class TestDemo {
 public function construct()
 {
  register_shutdown_function([$this, "f"], "hello");
 }
  
 public function f($str)
 {
  echo "class TestDemo->f():" . $str;
 }
}
  
$demo = new TestDemo();
echo &#39;before&#39; . PHP_EOL;
  
/**
运行:
before
class TestDemo->f():hello
 */


4. 同时调用多个

可以多次调用 register_shutdown_function,这些被注册的回调会按照他们注册时的顺序被依次调用。

不过注意的是,如果在第一个注册的中止方法里面调用exit方法或者是die方法的话,那么其他注册的中止回调也不会被调用。
代码:

<?php
/**
 * 可以多次调用 register_shutdown_function,这些被注册的回调会按照他们注册时的顺序被依次调用。
 * 注意:如果你在f方法(第一个注册的方法)里面调用exit方法或者是die方法的话,那么其他注册的中止回调也不会被调用
 */
  
/**
 * @param $str
 */
function f($str) {
 echo $str . PHP_EOL;
  
 // 如果下面调用exit方法或者是die方法的话,其他注册的中止回调不会被调用
 // exit();
}
  
// 注册第一个中止回调f方法
register_shutdown_function("f", "hello");
  
class TestDemo {
 public function construct()
 {
  register_shutdown_function([$this, "f"], "hello");
 }
  
 public function f($str)
 {
  echo "class TestDemo->f():" . $str;
 }
}
  
$demo = new TestDemo();
echo &#39;before&#39; . PHP_EOL;
  
/**
运行:
before
hello
class TestDemo->f():hello
  
注意:如果f方法里面调用了exit或者是die的话,那么最后的class TestDemo->f():hello不会输出
 */

   


5. 用处

该函数的作用:

析构函数:在PHP4的时候,由于类不支持析构函数,所以这个函数经常用来模拟实现析构函数

致命错误的处理:使用该函数可以用来捕获致命错误并且在发生致命错误后恢复流程处理

代码如下:

<?php
/**
 * register_shutdown_function,注册一个会在php中止时执行的函数,中止的情况包括发生致命错误、die之后、exit之后、执行完成之后都会调用register_shutdown_function里面的函数
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/15
 * Time: 17:41
 */
  
class Shutdown
{
 public function stop()
 {
  echo &#39;Begin.&#39; . PHP_EOL;
  // 如果有发生错误(所有的错误,包括致命和非致命)的话,获取最后发生的错误
  if (error_get_last()) {
   print_r(error_get_last());
  }
  
  // ToDo:发生致命错误后恢复流程处理
  
  // 中止后面的所有处理
  die(&#39;Stop.&#39;);
 }
}
  
// 当PHP终止的时候(执行完成或者是遇到致命错误中止的时候)会调用new Shutdown的stop方法
register_shutdown_function([new Shutdown(), &#39;stop&#39;]);
  
// 将因为致命错误而中止
$a = new a();
  
// 这一句并没有执行,也没有输出
echo &#39;必须终止&#39;;


运行:

Fatal error: Uncaught Error: Class &#39;a&#39; not found in D:\laragon\www\php_book\1_23_register_shutdown.php on line 31
  
Error: Class &#39;a&#39; not found in D:\laragon\www\php_book\1_23_register_shutdown.php on line 31
  
Call Stack:
 0.0060  362712 1. {main}() D:\laragon\www\php_book\1_23_register_shutdown.php:0
  
Begin.
Array
(
 [type] => 1
 [message] => Uncaught Error: Class &#39;a&#39; not found in D:\laragon\www\php_book\1_23_register_shutdown.php:31
Stack trace:
#0 {main}
 thrown
 [file] => D:\laragon\www\php_book\1_23_register_shutdown.php
 [line] => 31
)
Stop.


注意:PHP7中新增了Throwable异常类,这个类可以捕获致命错误,即可以使用try...catch(Throwable $e)来捕获致命错误,代码如下:

<?php
  
try {
 // 将因为致命错误而中止
 $a = new a();
  
 // 这一句并没有执行,也没有输出
 echo &#39;end&#39;;
} catch (Throwable $e) {
 print_r($e);
 echo $e->getMessage();
}


运行:

Error Object
(
 [message:protected] => Class &#39;a&#39; not found
 [string:Error:private] =>
 [code:protected] => 0
 [file:protected] => C:\laragon\www\php_book\throwable.php
 [line:protected] => 5
 [trace:Error:private] => Array
  (
  )
  
 [previous:Error:private] =>
 [xdebug_message] =>
Error: Class &#39;a&#39; not found in C:\laragon\www\php_book\throwable.php on line 5
  
Call Stack:
 0.0000  349856 1. {main}() C:\laragon\www\php_book\throwable.php:0
  
)
Class &#39;a&#39; not found

   


这样的话,PHP7中使用Throwable来捕获的话比使用register_shutdown_function这个函数来得更方便,也更推荐Throwable。

注意:Error类也是可以捕获到致命错误,不过Error只能捕获致命错误,不能捕获异常Exception,而Throwable是可以捕获到错误和异常的,所以更推荐。

6.巧用register_shutdown_function判断php程序是否执行完

还有一种应用场景就是:要做一个消费队列,因为某条有问题的数据导致致命错误,如果这条数据不处理掉,那么整个队列都会导致瘫痪的状态,这样可以用以下方法来解决。即:如果捕获到有问题的数据导致错误,则在回调函数中将这条数据处理掉就可以了。

php范例参考与解析:

<?php
 
register_shutdown_function(&#39;myFun&#39;); //放到最上面,不然如果下面有致命错误,就不会调用myFun了。
$execDone = false; //程序是否成功执行完(默认为false)
 
/**
********************* 业务逻辑区*************************
*/
$tas = 3;
if($tas == 3)
{
new daixiaorui();
}
 
/**
********************* 业务逻辑结束*************************
*/
$execDone = true; //由于程序由上至下执行,因此当执行到此后,则证明逻辑没有出现致命的错误。
 
function myFun()
{
global $execDone;
if($execDone === false)
{
file_put_contents("E:/myMsg.txt", date("Y-m-d H:i:s")."---error: 程序执行出错。\r\n", FILE_APPEND);
/******** 以下可以做一些处理 ********/
}
}

总结

register_shutdown_function这个函数主要是用在处理致命错误的后续处理上(PHP7更推荐使用Throwable来处理致命错误),不过缺点也很明显,只能处理致命错误Fatal error,其他的错误包括最高错误Parse error也是没办法处理的。


相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

相关阅读:

实例讲解Ajax异步请求技术

AJAX的常用语法是什么

AJAX原理与CORS跨域的方法


The above is the detailed content of Detailed introduction of register_shutdown_function function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
linux关机命令shutdown可以实现立刻关机吗linux关机命令shutdown可以实现立刻关机吗Jan 28, 2023 pm 05:26 PM

linux关机命令shutdown可以实现立刻关机,只需要root用户执行“shutdown -h now”命令即可。shutdown命令可以用来进行关机程序,并且在关机以前传送讯息给所有使用者正在执行的程序,shutdown命令需要系统管理者root用户来使用。

function是什么意思function是什么意思Aug 04, 2023 am 10:33 AM

function是函数的意思,是一段具有特定功能的可重复使用的代码块,是程序的基本组成单元之一,可以接受输入参数,执行特定的操作,并返回结果,其目的是封装一段可重复使用的代码,提高代码的可重用性和可维护性。

在 Windows 10 / 11 中设置自动关机的 3 种方法在 Windows 10 / 11 中设置自动关机的 3 种方法May 01, 2023 pm 10:40 PM

在繁忙的世界中,我们希望自动化一些您希望定期或及时触发的事情。自动化有助于控制任务并减少您执行任务的努力。其中一项任务可能是关闭您的计算机。您可能希望您的计算机定期关闭,或者您希望它在一天中的特定时间关闭,或者在一周中的特定日子关闭,或者您想要关闭一次。让我们看看如何设置计时器,以便系统自动关闭。方法一:使用运行对话框步骤1:按Win+R,键入shutdown-s-t600并单击OK。注意:在上面的命令中,600表示以秒为单位的时间。您可以根据需要更改它。它应该始终以秒为单位,而不是几分钟或几小

如何在Linux中设置定时关机命令如何在Linux中设置定时关机命令Feb 18, 2024 pm 11:55 PM

Linux定时关机命令是什么在使用Linux系统时,我们经常需要定时关机,比如在下载大量文件后自动关机,或者在服务器不再使用时自动关闭等。在Linux系统中,定时关机可以使用“shutdown”命令来实现。“shutdown”命令允许用户将系统关闭或重新启动,并设置一个延迟时间。通过在命令中添加参数,可以实现定时关机的功能。命令的基本格式如下:shutdow

MySQL shutdown unexpectedly - 如何解决MySQL报错:MySQL意外关闭MySQL shutdown unexpectedly - 如何解决MySQL报错:MySQL意外关闭Oct 05, 2023 pm 02:42 PM

MySQL是一款常用的关系型数据库管理系统,广泛应用于各种网站和应用中。然而,使用MySQL时可能会遇到各种问题,其中之一就是MySQL意外关闭。在这篇文章中,我们将讨论如何解决MySQL报错的问题,并提供一些具体的代码示例。当MySQL意外关闭时,我们首先应该查看MySQL的错误日志,以了解关闭的原因。通常,MySQL的错误日志位于MySQL安装目录的da

"enumerate()"函数在Python中的用途是什么?"enumerate()"函数在Python中的用途是什么?Sep 01, 2023 am 11:29 AM

在本文中,我们将了解enumerate()函数以及Python中“enumerate()”函数的用途。什么是enumerate()函数?Python的enumerate()函数接受数据集合作为参数并返回一个枚举对象。枚举对象以键值对的形式返回。key是每个item对应的索引,value是items。语法enumerate(iterable,start)参数iterable-传入的数据集合可以作为枚举对象返回,称为iterablestart-顾名思义,枚举对象的起始索引由start定义。如果我们忽

MySQL.proc表的作用和功能详解MySQL.proc表的作用和功能详解Mar 16, 2024 am 09:03 AM

MySQL.proc表的作用和功能详解MySQL是一种流行的关系型数据库管理系统,开发者在使用MySQL时常常会涉及到存储过程(StoredProcedure)的创建和管理。而MySQL.proc表则是一个非常重要的系统表,它存储了数据库中所有的存储过程的相关信息,包括存储过程的名称、定义、参数等。在本文中,我们将详细解释MySQL.proc表的作用和功能

shutdown马上关机命令是什么shutdown马上关机命令是什么Feb 27, 2023 am 11:23 AM

shutdown马上关机命令是“shutdown -h now”;其中shutdown命令可以用来进行关机程序,并且在关机以前传送讯息给所有使用者正在执行的程序,shutdown也可以用来重开机。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.