How to get the line number in PHP?

Asked

Viewed 620 times

2

How can I be getting the line number on which the method was executed for example?

class.php

Class Example
{
    function methodExample()
    {
        echo __LINE__;
    }
}

index php.

include "class.php";

Example::methodExample(); // 5

The use of _LINE_ does not do what I wish, since it displays the line where it was inserted and not where the method was called.

1 answer

4


Pass the number of the current line as argument for the method (it has to have a parameter to receive this argument). Or use the debug_backtrace() to get all call information (slower).

Class Example {
    function methodExample($line) {
        echo $line . "\n";
    }
    function methodExample2() {
        echo debug_backtrace()[0]["line"];
    }
}
Example::methodExample(__LINE__);
Example::methodExample2();

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.