【问题标题】:Determine What Line a Function Was Executed From [duplicate]确定从哪一行执行函数[重复]
【发布时间】:2010-02-02 18:25:28
【问题描述】:

我正在尝试构建一个错误类,我过去看过的很多错误类都使用 FILELINE 来显示错误发生的位置,但它们在函数中使用它们,所以它们总是相同的,这是非常无用的信息。除了使用每个函数发送包含 FILELINE 的数组(这会很痛苦),我想不出或找到其他任何东西。有没有好的方法或函数来确定执行函数的正确行号和文件?

例子:

<?php
// file1.php
dosomething(false);
?>

<?php
// file2.php
function dosomething($input) {
    if ($input === false) die("Error at Line (line) in File (file)");
}
?>

该函数将终止,并显示消息“文件 /file1.php 中的第 3 行出错”。

【问题讨论】:

    标签: php


    【解决方案1】:

    我想一个解决方案可能是使用debug_backtrace

    给定的例子得到这样的回溯:

    array(2) {
    [0]=>
    array(4) {
        ["file"] => string(10) "/tmp/a.php"
        ["line"] => int(10)
        ["function"] => string(6) "a_test"
        ["args"]=>
        array(1) {
          [0] => &string(6) "friend"
        }
    }
    [1]=>
    array(4) {
        ["file"] => string(10) "/tmp/b.php"
        ["line"] => int(2)
        ["args"] =>
        array(1) {
          [0] => string(10) "/tmp/a.php"
        }
        ["function"] => string(12) "include_once"
      }
    }
    

    所以,应该包括你想要的;-)


    而如果你只是想输出trace(不太可能),还有debug_print_backtrace

    【讨论】:

      【解决方案2】:

      检查 set_error_handler 函数: http://us3.php.net/manual/en/function.set-error-handler.php 您可能还想查看 set_exception_handler 函数。

      【讨论】:

        【解决方案3】:

        我在我的网站上使用的功能:

        <!DOCTYPE HTML>
        <html>
        <head>
        <title>Determine what line a function was executed from</title>
        </head>
        <body>
        <?php
            function linea($string1, $linea, $string2 = NULL)
            {
              $string2 = !empty($string2) ? $string2 : '';
              return $string1 . $linea . $string2;
            }
            echo linea('Error: ', __LINE__) . '<br />';
            /*
            ...
            lot of code
            ...
            */
            echo linea('Alert -> ', __LINE__, '!') . '<br />';
        ?>
        </body>
        </html>
        

        输出:

        Error: 13
        Alert -> 19!
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-25
          • 1970-01-01
          • 2013-10-24
          • 2013-09-07
          • 2016-11-15
          • 2016-12-09
          • 2016-01-31
          • 2019-07-09
          相关资源
          最近更新 更多