9个你必须知道的实用PHP函数

9、注册停止功能

有一个函数叫做 register_shutdown_function(),可以让你在某段脚本完成运行之前,执行一些指定代码。假设你需要在脚本执行结束前捕获一些基准统计信息,例如运行的时间长度:

1
2
3
4
5
6
7
8
9
10
// capture the start time
$start_time = microtime(true);
 
// do some stuff
// ...
 
// display how long the script took
echo "execution took: ".
		(microtime(true) - $start_time).
		" seconds.";

这似乎微不足道,你只需要在脚本运行的最后添加相关代码。但是如果你调用过 exit() 函数,该代码将无法运行。此外,如果有一个致命的错误,或者脚本被用户意外终止,它可能无法再次运行。当你使用 register_shutdown_function() 函数,代码将继续执行,不论脚本是否停止运行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$start_time = microtime(true);
 
register_shutdown_function('my_shutdown');
 
// do some stuff
// ...
 
function my_shutdown() {
	global $start_time;
 
	echo "execution took: ".
			(microtime(true) - $start_time).
			" seconds.";
}

英文原稿:9 Useful PHP Functions and Features You Need to Know | Nettuts

版权所有:为网站而疯狂-给站长一个五星级的家转载请注明来源,谢谢!

还不快抢沙发       我也不甘寂寞

欢迎留言

友情提示:
1、请勿发表色情、违法、商业广告等信息,谢谢。
2、留言想要有头像?请看 “我” 的。