是否有一种方法可以只退出包含的php文件


Is there a way to exit only the php file being included?

所以,我有一个sidebar.php是包含在index.php。在某种情况下,我想让sidebar.php停止运行,所以我想把exit放在sidebar.php中,但这实际上退出了它下面的所有代码,这意味着index.phpinclude('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 />";
    }
}