PHP提供register_shutdown_function()这个函数,能够在脚本终止前回调注册的函数,也就是当 PHP 程序执行完成后执行的函数。
egister_shutdown_function 执行机制是:PHP把要调用的函数调入内存。当页面所有PHP语句都执行完成时,再调用此 函数。注意,在这个时候从内存中调用,不是从PHP页面中调用,所以如果有路径信息,应使用绝对路径,因为PHP已经当原来的页面不存在了。就没有什么相对路径可言。
注意:register_shutdown_function是指在执行完所有PHP语句后再调用函数,不要理解成客户端关闭流浏览器页面时调用函数。
可以这样理解调用条件:
1、当页面被用户强制停止时
2、当程序代码运行超时时
3、当PHP代码执行完成时
示例代码:
<?php
namespace MySpace;
use Exception;
class MyArray {
static function triggerBeforeClose() {
$lastError = error_get_last ();
print ($lastError) ;
print_r ( "Called " );
}
}
// 注册时指明是哪个命名空间下的哪个类,要回调的方法名
register_shutdown_function ( array (
"MySpace\\MyArray",
"triggerBeforeClose"
) );
print_r ( "I'm the last line." );
print_r ( "\r\n" );
执行结果:
I'm the last line.
Called