如何查看调用的函数是否源自 PHP die()


How to see if a function called is originated from PHP die()

我有一个php函数create_error($error_string, $priority = false, $display_error = "")

$error_string = 错误消息。

$priority = 如果函数应仅将此消息显示在所有其他消息之上。 create_error使用全局变量将以前的所有错误消息存储在数组中。如果$priority === true那么它将只在数组中具有新消息,否则它将使用 array_push 添加新消息。

$display_error = 控件以突出显示错误消息。

function create_error($error_string, $priority = false, $display_error = "")
{
    global $json_responder;
    if ($priority === true) {
        $json_responder = array(array("typeof" => "message", "message" => translate($error_string)));
    } else {
        if (count($json_responder) >= 1) {
            array_push($json_responder, array("typeof" => "message", "message" => translate($error_string)));
        } else {
            $json_responder = array(array("typeof" => "message", "message" => translate($error_string)));
        }
    }
 // my ideal if died statement would be here.
 // like 
 // if(is_from_die() === true){
 // echo json_encode($json_responder);}
 }

我有以下一段代码:

$sql_code = "select username, password, login_allowed from user where current = 1 and username = '$username' and password = '$password' ";
$qrs = mysqli_query($sql,$sql_code) or die(create_error('E500.2 - internal server error.'));
if(mysqli_num_rows($qrs) >= 2 || mysqli_num_rows($qrs) === 0) die(create_error('Incorrect username / password combination.'));

因此,当此代码die(create_error('Incorrect username / password combination.'));运行时,它永远不会显示消息,因为它永远不会到达函数的末尾。

如何在我的 create_error 函数中确定它是否是从 PHP 中的die构造调用的?我已经尝试过返回debug_print_backtrace();

Array
    (
        [0] => Array
            (
                [file] => C:'Web'dev'core'request_initializer.php
                [line] => 83
                [function] => create_error
                [args] => Array
                    (
                        [0] => Incorrect username / password combination.
                    )
            )
        [1] => Array
            (
                [file] => C:'Web'dev'core'request_initializer.php
                [line] => 29
                [function] => request_login
                [args] => Array
                    (
                    )
            )
    )

是否有可能检测来自die()结构的天气?我在这里有很多解决方法,因为应用程序仍处于核心开发阶段,但我理想的选择是让 PHP "自动"检测die()exit()

我真的建议你使用异常,并且你实现你的自定义异常,而不是调用exit()die()内置函数......否则,现在,实现工作的唯一方法是像这样更改代码:

$qrs = mysqli_query($sql,$sql_code) or create_error('E500.2 - internal server error.', FALSE, "", TRUE);

function create_error($error_string, $priority = false, $display_error = "", $withExit = FALSE) {
    // do your stuf...
    // ...
    if($withExit === TRUE) {
        exit (0);
    }
}