我的页眉和页脚需要声明:
<?php
require "assets/php/header.php";
// Script goes here.
require "assets/php/footer.php";
?>
如果我在两个语句之间有一个脚本,我怎么能在脚本中有一个die()语句来结束当前脚本,但仍然显示页脚?如果没有办法做到这一点,还有其他选择吗?我个人认为需求陈述已经过时了,我想知道一些替代方案,或者只是更好的设置方法。提前谢谢。
答案 0 :(得分:0)
你应该使用例外。
尝试这样的事情:
<?php
try {
require "assets/php/header.php";
// Script goes here.
// replace "die();" with :
throw new Exception("I want to die");
// folowing code executed if no exception is thrown
require "assets/php/footer.php";
// end of "normal" case
} catch (Exception $e) {
// an exception makes footer and then dies
require "assets/php/footer.php";
die();
}
?>
如果使用不能触发页脚的异常,也可以使用此catch:
} catch (Exception $e) {
if($e->getMessage() == "I want to die") {
// an exception asks to make footer and then dies
require "assets/php/footer.php";
die();
} else {
throw $e;
}
}
或者如果你想让它变得干净,那就建立一个新的异常类(例如DieWithFooterException
)并像这样使用它:
<?php
try {
require "assets/php/header.php";
// Script goes here.
// replace "die();" with :
throw new DieWithFooterException();
// folowing code executed if no exception is thrown
require "assets/php/footer.php";
// end of "normal" case
} catch (DieWithFooterException $dwfe) {
// an exception asks to make footer and then dies
require "assets/php/footer.php";
die();
} catch (Exception $e) {
// stuff to do with other excpetions
}
?>
这就是说,最后一种解决方案是更好的方法:)