所以,我有一个sidebar.php是包含在index.php
。在某种情况下,我想让sidebar.php
停止运行,所以我想把exit
放在sidebar.php
中,但这实际上退出了它下面的所有代码,这意味着index.php
中include('sidebar.php');
下面的所有代码也将被跳过。有没有一种方法可以让exit
只跳过sidebar.php
中的代码?
只用return;
也要注意,以这种方式实际返回一些东西给调用脚本是可能的。
如果你的父脚本有$somevar = include("myscript.php");
,然后在myscript.php你说…return true;
你会得到$somevar
是的,您只需使用return;
。您的sidebar.php文件可能看起来像这样:
<?php
if($certain_condition) {
return;
} else {
// Do your stuff here
}
?>
我知道这是一个非常老的问题,但我最近接管了另一个开发人员的代码库,他虔诚地使用exit,这意味着包含各种文件的父文件必须以这样一种方式设计,即模块文件的包含在最后完成,所以它不会剪掉页面。我编写了一个小PHP脚本,将所有出现的"exit;"替换为"return;"。
if($handle = opendir("path/to/directory/of/files")) {
while(false !== ($file = readdir($handle))) {
if("." === $file) continue;
if(".." === $file) continue;
$pageContents = file_get_contents($file);
$pageContents = str_replace("exit;", "return;", $pageContents);
file_put_contents($file, $pageContents);
echo $file . " updated<br />";
}
}