当在函数中调用die()时会发生什么


What happens when die() is called within a function

我正在处理一个更新配置文件页面,有这样的东西来更新用户详细信息:

account.php

include_once('update_account.php');
$verify_credentials = checkcredentials($email, $password);
if ($verify_credentials == 1)
{
  $update_result = updateaccount($email, $newpassword);
}

update_account.php

session_start();
include_once('connect.php');
function updateaccount($email, $newpassword)
{
    $actcode = md5(uniqid(rand()));
    $update_query = mysqli_query($link, "UPDATE TABLE fu_user SET email = '$email', password = '$newpassword', is_activated='0', activation_code='$actcode' where email = '".$_SESSION['email']."'") or die ('Unable to Update');
      if($update_query){
        $_SESSION['email'] = $email;
        $_SESSION['activated'] = '0';
        $update_result = "Your Email and Password has been updated successfully.";
      }
return $update_result;
}

那么,如果查询执行失败并且调用了die(),会发生什么呢?updateaccount()会从调用它的位置返回任何内容吗?

据我所知,die()exit()完全相同,然后停止执行,并为其清理过程调用析构函数。

执行上述操作的其他方式是:

$update_query = mysqli_query($link, "UPDATE TABLE fu_user SET email = '$email', password = '$newpassword',
is_activated='0', activation_code='$actcode' where email = '".$_SESSION['email']."'");
if ($update_query)
{
    //Return Success
}
else
{
    //Return Failure
}

是,exitdie立即结束脚本执行。调用exit的函数不会返回任何内容,因为执行不会在正常流中继续。

正如你所写的,只有析构函数才会在之后调用:

即使使用exit()停止脚本执行,也会调用析构函数。在析构函数中调用exit()将阻止剩余的关闭例程执行。

在一种特殊情况下,您还可以注册一个在执行停止前调用的关闭函数:

注册要在脚本执行完成或调用exit()后执行的回调。

正如其他人所指出的,与其停止执行,不如实际处理错误状态。我认为您不希望向用户显示带有错误消息的空白页面。返回一个值,该值指示函数的错误状态,或者更好地使用异常并在更高级别上处理错误状态。

die()是PHP中的一个内置函数。它用于打印消息并退出当前PHP脚本。相当于exit()函数。

语法:

die($message)

参数:此函数只接受一个参数,该参数不是必须传递的。

$message:此参数表示退出脚本时要打印的消息。返回值:它没有返回值,但在退出脚本时打印给定的消息。