Home  >  Article  >  php教程  >  fatal error:php中通过register_shutdown_function记录fatal error

fatal error:php中通过register_shutdown_function记录fatal error

WBOY
WBOYOriginal
2016-06-21 08:50:111115browse

今天发现php中,如果要记录fatal error的时候,可以实用一个不错的函数,
叫register_shutdown_function,小结如下:
  register_shutdown_function可以让我们设置一个当执行关闭时可以被调用的另一个函数.也就是说当我们的脚本执行完成或意外死掉 导致PHP执行即将关闭时,我们的这个函数将会被调用.所以,我们可以使用在脚本开始处设置一个变量为false,然后在脚本末尾将之设置为true的方 法,让PHP关闭回调函数检查脚本完成与否. 如果我们的变量仍旧是false,我们就知道脚本的最后一行没有执行,因此它肯定在程序执行到某处死掉了;
   例子如下:
 

  1. ?php 
  2. $clean = false; 
  3. function shutdown_func(){ 
  4. global $clean
  5. if (!$clean){ 
  6. die("not a clean shutdown"); 
  7. return false; 
  8. register_shutdown_function("shutdown_func"); 
  9. $a = 1; 
  10. $a = new FooClass(); // 将因为致命错误而失败 
  11. $clean = true; 
  12. ?> 
  13. 再来一个记录fatal error的例子 
  14. function catch_fatal_error() 
  15. $last_error = error_get_last(); 
  16. // 检查是否属于fatal_error 
  17. if(isset($last_error['type']) &&$last_error['type']==E_ERROR) 
  18. //相关的处理 
  19. register_shutdown_function('catch_fatal_error'); 


  注意的是;
1,register_shutdown_function()函数可重复调用,但执行的顺序与注册的顺序相同
2,如果在调用register_shutdown_function()函数之前有exit()函数调用,register_shutdown_function()函数将不能执行
3,PHP4后支持注册函数参数传递
4,在某些服务端,如Apache,当前目录在register_shutdown_function()函数中能够改变
5,register_shutdown_function()函数执行在headers发送之后

本文链接http://www.cxybl.com/html/wlbc/Php/20130318/37221.html



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