代码之家  ›  专栏  ›  技术社区  ›  PHLAK

在另一个PHP页面中退出PHP脚本

  •  1
  • PHLAK  · 技术社区  · 17 年前

    我试图为我正在编写的PHP脚本实现缓存,但我一直遇到以下问题。我希望该脚本包含在其他PHP页面中,但当我尝试传递缓存文件并退出嵌入式脚本时,它会退出脚本和父页面,但不会解析父页面上的其余代码。请参阅下面的代码以获取示例。


    索引php

    <?php
      echo "Hello World!<br />";
    
      include("file2.php");
    
      echo "This line will not be printed";
    ?>
    


    file2.php

    <?php
      $whatever = true;
    
      if ($whatever == true) {
        echo "file2.php has been included<br />";
        exit; // This stops both scripts from further execution
      }
    
      // Additional code here
    ?>
    


    如果执行上述index.php,您将得到以下输出:

    Hello World! 
    file2.php has been included
    

    然而,我试图让它看起来像这样:

    Hello World! 
    file2.php has been included
    This line will not be printed
    
    4 回复  |  直到 12 年前
        1
  •  3
  •   Tom Haigh    17 年前

    使用 return; 而不是 exit; 在包含的文件中,这只会暂停该脚本的执行。

    请注意,您也可以使用它向父脚本返回一个值,例如。

    file1.php

    <?php
    echo 'parent script';
    $val = include('file2.php'); //$val will equal 'value'
    echo 'This will be printed';
    

    file2.php

    <?php
    echo 'child script';
    return 'value';
    
        2
  •  2
  •   Peter Bailey    17 年前

    只需将“这里的附加代码”包装在else语句中?

    <?php
      $whatever = true;
    
      if ($whatever == true) {
        echo "file2.php has been included<br />";
      } else {
        // Additional code here
      }
    ?>
    

    否则,我不知道你在说什么 退出 命令总是终止当前的整个执行,而不仅仅是当前文件的执行(对于当前文件,没有命令)

    编辑

    感谢PHLAK、tomhaigh、MichaelM和Mario的评论和帖子,我今天也学到了一些东西——你 控制器局域网 确实终止单个包含文件的执行 返回 命令。谢谢你们!

        3
  •  1
  •   Mario    17 年前

    我个人尽量避免在可能的情况下使用if-else条件,并使用(不确定是否有一个专门的术语,但)早期退出拦截条件。

    索引php

    <?php
    echo 'header';
    include 'content.php';
    echo 'footer';
    ?>
    

    content.php

    <?php
    if ($cached)
    {
        echo cached_version();
        return; // return is not just for functions, in php...
    }
    
    //proceed with echoing whatever you want to echo if there's no cached version.
    ...
    ...
    ?>
    
        4
  •  1
  •   BenMorel Manish Pradhan    12 年前

    为什么不将file2.php的内容封装到一个函数中呢。这样,您可以在需要时从函数返回,其余的执行不会停止。如:

    file2.php

    <?php
        // this function contains the same code that was originally in file2.php
        function exe() 
        {
            $whatever = true;
            if ($whatever)
            {
                echo "file2.php has been included <br />";
                // instead of exit, we just return from the function
                return;
            }
         }
    
         // we call the function automatically when the file is included
         exe();
    ?>
    

    让index.php保持原样,你应该会看到你想要实现的输出。