Detailed 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 '这个是中止方法test的输出'; } register_shutdown_function('test'); echo 'before' . PHP_EOL;
运行:
before
这个是中止方法test的输出
注意:输出的顺序,等执行完成了之后才会去执行register_shutdown_function的中止方法test
b. 第二种情况,exit/die导致的中止
<?php function test() { echo '这个是中止方法test的输出'; } register_shutdown_function('test'); echo 'before' . PHP_EOL; exit(); echo 'after' . PHP_EOL;
运行:
before
这个是中止方法test的输出
后面的after并没有输出,即exit或者是die方法导致提前中止。
c. 第三种情况,发送致命错误中止
<?php function test() { echo '这个是中止方法test的输出'; } register_shutdown_function('test'); echo 'before' . PHP_EOL; // 这里会发生致命错误 $a = new a(); echo 'after' . PHP_EOL;
运行:
before Fatal error: Uncaught Error: Class 'a' not found in D:\laragon\www\php_book\test.php on line 1 Error: Class 'a' 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(), 'stop']); // 将因为致命错误而中止 $a = new a(); // 这一句并没有执行,也没有输出 echo '必须终止';
也可以在类中执行:
<?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 'before' . 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 'before' . 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 'Begin.' . PHP_EOL; // 如果有发生错误(所有的错误,包括致命和非致命)的话,获取最后发生的错误 if (error_get_last()) { print_r(error_get_last()); } // ToDo:发生致命错误后恢复流程处理 // 中止后面的所有处理 die('Stop.'); } } // 当PHP终止的时候(执行完成或者是遇到致命错误中止的时候)会调用new Shutdown的stop方法 register_shutdown_function([new Shutdown(), 'stop']); // 将因为致命错误而中止 $a = new a(); // 这一句并没有执行,也没有输出 echo '必须终止';
运行:
Fatal error: Uncaught Error: Class 'a' not found in D:\laragon\www\php_book\1_23_register_shutdown.php on line 31 Error: Class 'a' 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 'a' 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 'end'; } catch (Throwable $e) { print_r($e); echo $e->getMessage(); }
运行:
Error Object ( [message:protected] => Class 'a' 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 'a' 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 'a' not found
这样的话,PHP7中使用Throwable来捕获的话比使用register_shutdown_function这个函数来得更方便,也更推荐Throwable。
注意:Error类也是可以捕获到致命错误,不过Error只能捕获致命错误,不能捕获异常Exception,而Throwable是可以捕获到错误和异常的,所以更推荐。
6.巧用register_shutdown_function判断php程序是否执行完
还有一种应用场景就是:要做一个消费队列,因为某条有问题的数据导致致命错误,如果这条数据不处理掉,那么整个队列都会导致瘫痪的状态,这样可以用以下方法来解决。即:如果捕获到有问题的数据导致错误,则在回调函数中将这条数据处理掉就可以了。
php范例参考与解析:
<?php register_shutdown_function('myFun'); //放到最上面,不然如果下面有致命错误,就不会调用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中文网其它相关文章!
相关阅读:
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools