1

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


索引.php

<?php
  echo "Hello World!<br />";

  include("file2.php");

  echo "This line will not be printed";
?>


文件2.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

4 回答 4

3

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

请注意,您还可以使用它向父脚本返回值,例如

文件1.php

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

文件2.php

<?php
echo 'child script';
return 'value';
于 2009-02-11T09:49:08.683 回答
2

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

<?php
  $whatever = true;

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

否则我不确定你在说什么。exit命令总是终止整个当前的执行——不仅仅是当前文件的执行(没有命令)

编辑

感谢 PHLAK、tomhaigh、MichaelM 和 Mario 的评论和帖子,我自己今天学到了一些东西——你确实可以使用return命令终止单个包含文件的执行。多谢你们!

于 2009-02-11T06:31:24.710 回答
1

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

文件2.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 保持原样,您应该会看到您想要实现的输出。

于 2009-02-11T06:34:49.960 回答
1

我个人尽量避免 if-else 条件并使用(不确定是否有一个创造的术语但是)提前退出拦截条件。

索引.php

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

内容.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.
...
...
?>
于 2009-02-11T09:56:35.763 回答