php的register_shutdown_function函数详解

80酷酷网    80kuku.com

  >

PHP提供register_shutdown_function()这个函数,能够在脚本终止前回调注册的函数

register_shutdown_function例子代码:

以下为引用的内容:

 <?php
function Test()
{      if(!file_exists('Test.txt')){     //判断如果文件不存在!!
echo '文件不存在,我要创建一个:';
        $Str = fopen('Test.txt',"w+");       
        fwrite($Str,'you are write after exit');
        fclose($Str);
echo "创建完成!";
}else {                           //如果存在;
        echo '文件已经存在';
}
}
register_shutdown_function('Test');
for($i=0;$i<10;$i++){
 echo "Echo<br/>";
}
exit;
?>

 There is a note "Shutdown function is called during the script shutdown so headers are always already sent.", but my php 5.1 seems to act differently.
Example:

以下为引用的内容: <?php
class Test {
  
   private $running;
  
   public function main() {
       $this->running = true;
       ob_start();
       error_reporting(E_ALL);
       register_shutdown_function(array($this, "clean_exit"));
       echo "Hello";
       // triggers E_ERROR
       $fatal->error();
      
       $this->running = false;   
   }

 

   public function clean_exit() {
       if ($this->running) {
           header("Location: error.php");   
       }   
   }
}
$t = new Test();
$t->main();
?>
This example redirects you on error.php, this could be a simple way to handle E_ERROR.

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: