anon
anon

Reputation:

knowing where a func has been called

I have a simple function

function hi(){
    echo 'hi';
    echo 'this func is called from: {file} at line {line}';
}

is there a way to know file and line that called a func inside the func?

Upvotes: 0

Views: 59

Answers (1)

alexn
alexn

Reputation: 59012

You can use debug_backtrace, like so:

function hi() {
    echo 'hi';

    $trace = debug_backtrace();
    $file = $trace[0]['file'];
    $line = $trace[0]['line'];

    echo 'this func is called from: ' . $file . ' at line ' . $line;
}

hi();

Note that debug_backtrace will fetch the entire call stack. The first element ($trace[0]) will always contain the calling line/function/file whatever.

Upvotes: 2

Related Questions