ajax 发表于 2008-10-25 23:38:28

php的register_shutdown_function函数详解

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.
页: [1]
查看完整版本: php的register_shutdown_function函数详解

网站推广