在php中向用户显示错误/消息的好方法是什么? [英] Whats a good way to show errors/messages to users in php?

查看:71
本文介绍了在php中向用户显示错误/消息的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多年以来,我一直在使用自己的方法,但我认为这并不是解决问题的最佳方法。

I have been using my own method for years, but I figured maybe its not the best way to go about it.

基本上,当我想抛出错误时给用户,或显示对成功操作的确认,我将执行以下操作:

Essentially when I want to throw an error to a user, or display confirmation of a successful action, I do the following:

if($something == "condition") {

   $_SESSION["message"] = "Your passwords didnt match! Make sure they are the same in both fields!";
   $_SESSION["message_type"] = 1;
   header("Location:register.php");
   exit();

}

然后我有一个类似

function show_message() {
   global $_SESSION;

   if (isset($_SESSION["message"])) { 
      echo "<div class='site_message type_" . $_SESSION["message_type"] . "'>" . $_SESSION["message"] . "</div>"; 
      unset($_SESSION["message"]); 
      unset($_SESSION["message_type"]); 
   }
}

,然后输入show_message();在每个页面的顶部显示可能抛出的错误。

and I put show_message(); on top of every page to display possible errors that might be throw to this page.

这可能有什么问题?

推荐答案

我认为这种方法没有错。您会在许多框架中以不同的名称找到该技术,例如 Zend Framework中的FlashMessenger
通常将Session封装在一个对象中,而不是常规的Session数组中,并使用ViewHelper而不是一个函数。

I see nothing wrong with this approach. You'll find this technique under different names in quite a number of frameworks, for instance FlashMessenger in Zend Framework. Usually the Session is wrapped in an object instead of the regular Session array and with a ViewHelper instead of a function.

请确保您没有分配消息时,会话键中的任何拼写错误,都可以将分配代码也包装到一个函数中,例如

To make sure you don't have any typos in the Session keys when assigning the message, you could wrap the assigning code into a function as well, e.g.

function set_message($text, $type)
{
    $_SESSION['message'] = array(
        'text' => $text,
        'type' => $type
    );
}

您可以通过使用 return 函数对其进行改进字符串,而不是 echo ,我个人将使用 sprintf 格式化输出。使代码更具可读性,例如

You could improve it by having the function return the string instead of echoing it and personally I'd use sprintf to format the output. Makes the code somewhat more readable imho, e.g.

return sprintf('<div id="message-box" class="type-%s">%s</div>',
                $_SESSION["message"]["text"], 
                $_SESSION["message"]["type"]);

就像@Gumbo指出的那样,当Sessions无法正常工作时,该功能可能无法正常工作,但很可能然后对整个应用程序施加了许多其他问题,因此我就不会再为这段特定代码而烦恼了。

Like @Gumbo pointed out, the function might not work when Sessions do not work, but that will likely impose a number of other problems for the entire application then, so I wouldn't exactly bother about this particular piece of code then.

次要问题:$ _SESSION是< a href = http://de2.php.net/manual/en/language.variables.superglobals.php rel = nofollow noreferrer>超全局,因此您不必使用全局关键字。

Minor thing: $_SESSION is a superglobal, so you do not have to use the global keyword.

这篇关于在php中向用户显示错误/消息的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆