我正在尝试为我正在编写的PHP脚本实现缓存,但我一直遇到以下问题。我希望脚本包含在其他PHP页面中,但是当我尝试传递缓存文件并退出嵌入式脚本时,它会退出脚本和父页面,但不解析父页面上的其余代码。请参阅下面的代码以获取示例。
的的index.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
答案 0 :(得分:3)
在包含的文件中使用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';
答案 1 :(得分:2)
只需在else语句中包含“附加代码”吗?
<?php
$whatever = true;
if ($whatever == true) {
echo "file2.php has been included<br />";
} else {
// Additional code here
}
?>
否则我不确定你得到了什么。 退出命令总是终止当前执行 - 而不仅仅是执行当前文件(没有命令)
感谢PHLAK,tomhaigh,MichaelM和Mario的评论和帖子,我自己今天学到了一些东西 - 你 CAN 确实终止了单个包含文件的执行w / 返回命令。谢谢,伙计们!
答案 2 :(得分:1)
为什么不将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,你应该看到你想要实现的输出。
答案 3 :(得分:1)
我个人尽量避免if-else条件尽可能使用(不确定是否有一个创造的术语,但是)提前退出拦截条件。
<强>的index.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.
...
...
?>