Determine from which line the function was executed.

I am trying to create an error class and many error classes that I looked at in the past, use FILE and LINE to show where the error occurred, but they use them in the function, so they are always the same, which is extremely useless information. Besides sending an array containing FILE and LINE with each function (which can be pretty painful), I can't think of or find anything else. Is there a good way or function to determine the correct line number and the file from which the function was executed?

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 will die with the message "Error on line 3 in / file 1.php."

+3
3

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

, , ; -)


(), debug_print_backtrace.

+4

set_error_handler: http://us3.php.net/manual/en/function.set-error-handler.php set_exception_handler.

0

The function that I use 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
source

Source: https://habr.com/ru/post/1731063/


All Articles