开发者

Determine What Line a Function Was Executed From [duplicate]

This question already has answers here: Get code line and file that's executing the current function in PHP? (3 answers) Closed 9 years ago.

I'm trying to build an error class and a lot of error classes I've looked at in the past use FILE and LINE to show where the error occurred, but they use them in the function so they're always the same, which is highly useless information. Aside from sending an array of containing FILE and LINE with every function (which would get to be quite a pain), I can't think of or find anything else. Is there a good way or a function out there to开发者_如何学Go determine the correct line number and file that the function was being executed from?

Example:

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

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

The function would die with the message "Error at Line 3 in File /file1.php".


I suppose a solution could be to use debug_backtrace.

The given example gets a backtrace like this :

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"
  }
}

So, should include what you want ;-)


And if you just want to output the trace (not likely), there is also debug_print_backtrace.


Check set_error_handler function: http://us3.php.net/manual/en/function.set-error-handler.php You may also want to look on set_exception_handler function.


The function I'm using on my sites:

<!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>

Outputs:

Error: 13
Alert -> 19!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜