phpmagic-constants

How to get the name of the script calling a function?


I want to write a very generic function for logging :

function msglog($type, $message) {
echo date("r") . " " . __FILE__ . " - $type - $message" . PHP_EOL;
}

I am going to use it almost everywhere in my code which will be dispatched in several php scripts include. As shown here, wherever the function is called, __FILE__ is always valued with the main script filename.

Is there a way I can get in the function itself the name of the caller script without having to pass it as a parameter ?

EDIT1 - it is not a duplicate

Eventhough the aim is to retrieve caller information, just like some other questions asked and the solution is the same. Knowing the answer make it obvious they are connected. My question had another "scope". It is relative to includes and script filename retrieval, not the function name in an unknown context.

EDIT2 - The answer

Yes, the debug_backtrace() function is the answer.

Here is the solution I was looking for :

function msglog( $type, $message) {
    $caller = debug_backtrace();
    echo date("r") . $caller[0]["file"] . " - $type - $message" . PHP_EOL;
}

Solution

  • Try:

    $caller = debug_backtrace();
    $caller = $caller[1];
    echo $caller['function'];
    

    you should get the name of the last function called

    function msglog($type, $message) {
        $caller = debug_backtrace();
        $caller = $caller[1];
        echo date("r") . " " . $caller['function'] . " - $type - $message" . PHP_EOL;
    }
    

    Yor can also get other informations:

    "file" => (string) "caller_filename.php"
    "line" => (int) number of line in caller_filename.php
    "function" => (string) "function name"