I've looked this up and I know that the answer probably involves the use of debug_backtrace()
, but I am struggling on how to use it or exactly what it does.
Basically, if this was index.php:
<?php
//some code
//some more code
require "functions.php";
print_line();
//some code
print_line();
?>
and functions.php was:
<?php
function print_line(){
$line="[line that this function was called at]";
print "This function was called from line $line of index.php<br />";
}
?>
What would be the correct way of setting $line
so that the output would be:
This function was called from line 7 of index.php
This function was called from line 11 of index.php
debug_backtrace() contains all nested function calls all the way to the current scope indexing from 0 (the closest).
So when you need the line where print_line() was called, just go with:
<?php
function print_line(){
$backtrace = debug_backtrace();
$line=$backtrace[0]['line'];
print "This function was called from line $line of index.php<br />";
}
Or as of PHP 5.4:
$line=debug_backtrace()[0]['line'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With