题
假设我有一些这样的代码:
<html>
<head><title>Title</title></head>
<body>
<?php
if (!$someCondition){
die();
}
else{
#Do something
}
?>
</body>
<html>
我希望这段代码的目的很简单。如果满足某个条件(即无法连接到数据库),那么程序应该死掉,否则它应该执行。执行die()函数时出现问题。它在那里停止正确,并且只将前三行发送到浏览器,而不是最后两行。
是否有一个功能,我可以使用而不是die(),以便php块将停止执行,但静态HTML文本仍然通过?
解决方案
您应该将页眉和页脚分隔成单独的文件和函数。这使得UI更易于维护,并使呈现视图的内容保持一致。结合使用异常处理,你就是黄金。
<?php
printHeader(); // outputs the html header
try
{
if (some condition)
{
throw new Exception("It Died...");
}
// More processing here that should not execute if the above condition is true
// ...
}
catch (Exception e)
{
echo $e->getMessage();
}
printFooter(); // outputs the html footer
?>
其他提示
将程序逻辑与演示文稿分离。阅读MVC,模板。
最简单的形式就是这样:
<?php
function logic() {
if (!$someCondition) {
return 'display_empty_page';
} else {
return 'display_other_stuff';
}
}
presentation(logic());
结果
对于其他情况,die()
或类似情况是不可避免的(例如致命错误或第三方代码死亡),有涉及输出处理程序的黑客攻击:
ob_start('myhandler');
function myhandler($page) {return $page.' extra markup';}
die();
虽然我建议仅将其用于诊断/调试目的。
将die传递给静态文本的参数。
例如改变这个:
<html>
<head><title>Title</title></head>
<body>
<?php
if (!$someCondition){
die();
}
else{
#Do something
}
?>
</body>
<html>
对此:
<html>
<head><title>Title</title></head>
<body>
<?php
if (!$someCondition){
die("OMG RED ALERT!!!!</body></html>");
}
else{
#Do something
}
?>
</body>
<html>
我可能会使用例外。将所有内容包装在try / catch块中,然后在数据库失败等错误情况下抛出新异常。你可以在catch块中做任何事情(比如一个空的die()方法),但最好在这里向用户提供一条错误信息。
以下是关于PHP5中异常处理的非常好的指南不熟悉它们,或者你需要了解自PHP4以来发生的变化。
您是否考虑过使用 register_shutdown_function
(php.net)完成加载页面?它应该能够处理die()
和exit()
。
如果你查看 PHP文档,你会看到<!>“;相当于<!>出口()QUOT; - 即调用它会终止你的程序,并没有给你很多机会做任何事情。即使在ZF之外,当应用程序die()时,你也无法做很多事情。解决方案是使用例外。
未捕获的异常与die()基本相同(除了生成的堆栈跟踪之外)。异常给你的是能够将它放在try / catch块中,让你有机会纠正错误并继续使用程序(或显示友好的错误消息并生成日志)。假设您正在使用Zend_Controller_Front,您可以查看 Zend Framework快速入门,看看它们是如何制作的一个默认的错误处理程序,它将捕获未捕获的异常并显示相应的错误消息。
一种方法可行,但不是我正在寻找的方法,将die()
替换为die("</body></html>")
。如果要返回的文本比这更复杂,那么它可以存储在变量中。还有什么比这更好的吗?
die()
可能不完全是你想要的。为什么不替换
if (!$someCondition) {
die();
} else {
/* do stuff */
}
带
if ($someCondition) {
/* do stuff */
} else {
/* output error message/redirect/output nothing/whatever */
}
或抛出/捕获异常?
如果你正在使用PHP4,或者只是不想打扰异常,那么你可以使用这种技术:
<html>
<head><title>Title</title></head>
<body>
<?php
do {
if (!$someCondition){
break;
} else {
#Do something
}
} while (0);
?>
</body>
<html>
..虽然有些人似乎非常反对使用这种风格,但有适当的评论,我认为没有任何问题。我要说它比重复你的<!>“页脚<!>”要好得多;每个die()语句中的代码。
<html>
<head><title>Title</title></head>
<body>
<?php
if (!$someCondition){
header ("location:error_page.php?erro_message='This error occured'");
die();
}
else{
#Do something
}
?>
</body>
<html>
error_page.php
header
echo $_GET[$error_message];
footer