我有一个sidebar.php文件,在index.php中引入。在某些情况下,我希望sidebar.php停止运行,因此我考虑在sidebar.php中使用exit退出,但这会导致其下面的所有代码都停止运行,也就是说,包括index.php中所有在include('sidebar.php');之后的代码都被跳过了。有没有一种方法可以让exit仅跳过sidebar.php中的代码?
我有一个sidebar.php文件,在index.php中引入。在某些情况下,我希望sidebar.php停止运行,因此我考虑在sidebar.php中使用exit退出,但这会导致其下面的所有代码都停止运行,也就是说,包括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 />";
}
}
我希望这能对某些人有所帮助。