Home > php教程 > php手册 > body text

PHP register_shutdown_function函数详解

WBOY
Release: 2016-06-13 10:48:07
Original
1167 people have browsed it

脚本时常死掉,而且并不总是那么好看. 我们可不想给用户显示一个致命错误,又或者一个空白页(在display_errors设为off的情况下) .
 
  PHP中有一个叫做register_shutdown_function 的函数,可以让我们设置一个当执行关闭时可以被调用的另一个函数.也就是说当我们的脚本执行完成或意外死掉导致PHP执行即将关闭时,我们的这个函数将会 被调用.所以,我们可以使用在脚本开始处设置一个变量为false,然后在脚本末尾将之设置为true的方法,让PHP关闭回调函数检查脚本完成与否.
 
  如果我们的变量仍旧是false,我们就知道脚本的最后一行没有执行,因此它肯定在程序执行到某处死掉了.我准备了一个非常基本的例子,可以演示在一个致 命错误需要显示时,你应该怎么给用户一些合适的反馈.你可以通过关闭致命错误的显示(译注:可以设置display_errors和error_reporting),让例子看起来好看些.
 
    
  $clean = false; function shutdown_func(){ global $clean; if (!$clean){ die("not a clean shutdown"); } return false; } register_shutdown_function("shutdown_func"); $a = 1; $a = new FooClass(); // 将因为致命错误而失败$clean = true; ?>
 
  正如你所看到,如果关闭回调函数运行时,clean变量没有被设为true,shutdown_func函数将会打印出一些东西.这个东西可以包装成一个类(不使用全局变量).
 
  PHP提供register_shutdown_function()这个函数,能够在脚本终止前回调注册的函数,也就是当PHP 程序执行完成后执行的函数。
 
  php程序员站
 
  例子:
 
  
 
  

register_shutdown_function绀轰
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!