Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the line that the function was called at? [duplicate]

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
like image 642
RedRocker227 Avatar asked Oct 21 '25 12:10

RedRocker227


1 Answers

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'];
like image 192
svecon Avatar answered Oct 23 '25 02:10

svecon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!