【问题标题】:Can a PHP script execute common code before exit()?PHP 脚本可以在 exit() 之前执行通用代码吗?
【发布时间】:2010-11-29 00:02:52
【问题描述】:

如何在 PHP 脚本中完成以下操作?

 code{
      $result1 = task1() or break;
      $result2 = task2() or break;
 }

 common_code();
 exit();

【问题讨论】:

    标签: php scripting webserver


    【解决方案1】:

    如果您使用 OOP,那么您可以将要在退出时执行的代码放入类的析构函数中。

    class example{
       function __destruct(){
          echo "Exiting";
       }
    }
    

    【讨论】:

      【解决方案2】:

      从 PHP 帮助文档中,您可以指定在 exit() 之后但在脚本结束之前调用的函数。

      请随时查看文档以获取更多信息http://us3.php.net/manual/en/function.register-shutdown-function.php

      <?php
      function shutdown()
      {
          // This is our shutdown function, in 
          // here we can do any last operations
          // before the script is complete.
      
          echo 'Script executed with success', PHP_EOL;
      }
      
      register_shutdown_function('shutdown');
      ?>
      

      【讨论】:

        【解决方案3】:

        您的示例可能过于简单,因为它可以很容易地重写如下:

        if($result1 = task1()) {
            $result2 = task2();
        }
        
        common_code();
        exit;
        

        也许您正在尝试像这样构建流控制:

        do {
            $result1 = task1() or break;
            $result2 = task2() or break;
            $result3 = task3() or break;
            $result4 = task4() or break;
            // etc
        } while(false);
        common_code();
        exit;
        

        您也可以使用switch()

        switch(false) {
        case $result1 = task1(): break;
        case $result2 = task2(): break;
        case $result3 = task3(): break;
        case $result4 = task4(): break;
        }
        
        common_code();
        exit;
        

        或者在 PHP 5.3 中你可以使用goto:

        if(!$result1 = task1()) goto common;
        if(!$result2 = task2()) goto common;
        if(!$result3 = task3()) goto common;
        if(!$result4 = task4()) goto common;
        
        common:
        echo "common code\n";
        exit;
        

        【讨论】:

          猜你喜欢
          • 2012-03-26
          • 2012-01-28
          • 1970-01-01
          • 2014-08-17
          • 2011-04-14
          • 1970-01-01
          • 2019-10-03
          • 2018-05-15
          • 1970-01-01
          相关资源
          最近更新 更多