正确使用 die()?

发布于 2024-09-05 17:26:20 字数 816 浏览 12 评论 0原文

注意:我正在使用输出缓冲。它只是包装在 head() 和 foot() 函数中。

我使用以下模板在当前的 PHP 项目中创建页面:

<?php
include 'bootstrap.php';
head();
?>

<!-- Page content here -->

<?php
foot();
?>

以下示例是否适当使用 die()?另外,这可能会给我带来什么样的问题(如果有的话)?

<?php
include 'bootstrap.php';
head();

try
{
    //Simulate throwing an exception from some class
    throw new Exception('Something went wrong!');
}
catch(Exception $e)
{
    ?>
    <p>Please fix the following error:</p>
    <p><?php echo $e->getMessage(); ?></p>
    <?php
    foot();
    die();
}

//If no exception is thrown above, continue script
doSomething();
doSomeOtherThing();

foot();
?>

基本上,我有一个包含多个任务的脚本,我试图设置一种优雅的方式来通知用户输入错误,同时防止脚本的其余部分执行。

谢谢!

Note: I am using output buffering. It's just wrapped in the head() and foot() functions.

I create pages in my current PHP project by using the following template:

<?php
include 'bootstrap.php';
head();
?>

<!-- Page content here -->

<?php
foot();
?>

Is the following example an appropriate use of die()? Also, what sort of problems might this cause for me, if any?

<?php
include 'bootstrap.php';
head();

try
{
    //Simulate throwing an exception from some class
    throw new Exception('Something went wrong!');
}
catch(Exception $e)
{
    ?>
    <p>Please fix the following error:</p>
    <p><?php echo $e->getMessage(); ?></p>
    <?php
    foot();
    die();
}

//If no exception is thrown above, continue script
doSomething();
doSomeOtherThing();

foot();
?>

Basically, I have a script with multiple tasks on it and I am trying to set up a graceful way to notify the user of input errors while preventing the remaining portion of the script from executing.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

娇纵 2024-09-12 17:26:20

我会这样做:

head();
try {
    somethingPossiblyWithError();
    somethingElse();
} catch (Exception $e) {
    handleError();
}
foot();

不需要死亡。如果在 somethingPossulousWithError 中引发错误,则 somethingElse 将被跳过。 foot 在这两种情况下都会被执行。

更新:我赞成Shrapnel上校的回答,因为我猜你没有考虑到这一点,这是一个有价值的知识。在 PHP 中,您可以通过 输出缓冲 获得等效功能,而无需显式传递周围的值,但它并不那么漂亮 - 但是,如果您调用将打印内容而不将它们作为值返回的函数,它会起作用,所以有时了解它很有用。

I'd do this:

head();
try {
    somethingPossiblyWithError();
    somethingElse();
} catch (Exception $e) {
    handleError();
}
foot();

No deaths necessary. If an error is raised in somethingPossiblyWithError, then somethingElse will get skipped. foot will get executed in both cases.

UPDATE: I upvoted Col. Shrapnel's answer, since I guess you did not think about that, and that is a valuable piece of knowledge. In PHP, you can get an equivalent functionality by output buffering, without explicitly passing values around, but it's not as pretty - however, it works if you are calling functions which will print things and not return them as values, so sometimes it's useful to know.

错々过的事 2024-09-12 17:26:20

整个页面结构错误。
尽管这是最常见的新手错误。

在准备好所有数据之前,永远不要输出任何东西。
您的脚本可能会发送一些 HTTP 标头,可能会设置一些在 header() 或其他内容中使用的变量。

因此,模板的使用是必要的。
您必须将脚本分为两部分 - 获取数据部分和显示数据部分。
因此,您必须将 header() 函数移至更低的位置。
根据 Amadan 的回答,

<?php
include 'bootstrap.php';
try {
  getData();
} catch (Exception $e) {
    handleError();
}
head();
body();
foot();
?>

handleError() 函数可能会设置适当的 HTTP 错误代码(404 或 500),并用错误消息文本替换正文模板。

The whole page structure is wrong.
Though it's most widespread newbie mistake.

One should never output a thing before having all data ready.
Your script may send some HTTP headers, may set up some variables for use in the header() or anything.

Therefore, template use is necessary.
You have to divide your script into 2 parts - getting data part and displaying data part.
So, you have to move header() function much lower.
And based on the Amadan's answer it could be

<?php
include 'bootstrap.php';
try {
  getData();
} catch (Exception $e) {
    handleError();
}
head();
body();
foot();
?>

handleError() function may set appropriate HTTP error code (404 or 500) and substitute body template with error message text.

你没皮卡萌 2024-09-12 17:26:20

由于多种原因,不推荐您的方法。你应该:

  • 分离表示和逻辑(看看 MVC 模式)
  • 避免过程代码,编写面向对象的 PHP
  • 分离用户和管理体验(温和地处理错误)

示例,实现上面:

<? $page->debug = true; ?>
<?= $page->getHead(); ?>
<?= $page->getBody(); ?>
<?= $page->getFoot(); ?>

class page {

   public debug;

   public function getBody() {
       try {
          //
       } catch (Exception $e) {
          $this->_errorhandler('message');
       }
   }

   protected function _errorhandler($message) {
        if ($this->debug) {
              // display error message
          } else {
             // display nothing, log the error
             // or throw concrete exception
             // or redirect
          }
   }
 ...
}

这也不推荐(有很多单独的代码)每个任务所需的类),但您会看到要点:分离而不是混合所有内容。

Your approach is not recommended for many reasons. You should:

  • separate the presentation and the logic (take a look at MVC pattern)
  • avoid procedural code, write object oriented PHP
  • separate user and admin experience (handle errors gently)

Example, implementing above:

<? $page->debug = true; ?>
<?= $page->getHead(); ?>
<?= $page->getBody(); ?>
<?= $page->getFoot(); ?>

class page {

   public debug;

   public function getBody() {
       try {
          //
       } catch (Exception $e) {
          $this->_errorhandler('message');
       }
   }

   protected function _errorhandler($message) {
        if ($this->debug) {
              // display error message
          } else {
             // display nothing, log the error
             // or throw concrete exception
             // or redirect
          }
   }
 ...
}

This is not recommended too (there are many separate classes needed for each task), but you see the point: separating, not mixing everything.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文