register_shutdown_function 这个函数是什么?
注册一个方法会在php执行终止时候执行
如何注册register_shutdown_function
define('START_TIME',$_SERVER['REQUEST_TIME_FLOAT']); register_shutdown_function(function(){ /** 一般我们要做的事情 1.整体项目执行时间 2.日志直接收集入库 3.出现错误相关收集 error_get_last() error_log(); //这个函数可以记录相关日志,但是不推荐使用,每一次都会写入 会对IO 造成很大的负担 **/ });
通过上边的方法,就可以注册一个 shutdown_function 方法
php中可以定义多个register_shutdown_function
执行顺序 按照 注册 register_shutdown_function 的顺序执行
代码实例:
<?php error_reporting(-1); ini_set('display_errors',1); define('START_TIME',microtime(true)); register_shutdown_function(function(){ $log=[]; $log[]='我是1号 register_shutdown_function'; $log[]='测试 多个 register_shutdown_function'; $log[]='按照 register_shutdown_function 的注册顺序执行 '; file_put_contents(__DIR__.'/relog.txt', implode("\n", $log),FILE_APPEND); }); register_shutdown_function(function(){ $endtime=microtime(true); $log=[]; $log[]=''; $log[]='我是2号 register_shutdown_function'; $log[]='系统执行消耗了'.(($endtime-START_TIME)*1000).'ms'; $log[]='耗时rsf'; file_put_contents(__DIR__.'/relog.txt', implode("\n", $log),FILE_APPEND); }); echo 111;
执行结果:
我是1号 register_shutdown_function 测试 多个 register_shutdown_function 按照 register_shutdown_function 的注册顺序执行 我是2号 register_shutdown_function 系统执行消耗了0.71406364440918ms 耗时rsf
如何终止register_shutdown_function
使用php的 exit 函数来终止
die 函数 来终止
register_shutdown_function会不执行吗? 在什么情况下?
register_shutdown_function 会有不执行的时候。
Note:
如果进程被信号SIGTERM或SIGKILL杀死,那么中止函数将不会被调用。尽管你无法中断SIGKILL,
但你可以通过pcntl_signal() 来捕获SIGTERM,通过在其中调用exit()来进行一个正常的中止。