Search code examples
phpdebugginglate-static-bindingdebug-backtrace

PHP use late static binding to get calling function?


Is it possible to get information (filename, line, function ...) of the calling function by using late static binding?

<?php
class Log{
    public static function write($msg){
        $line = ??;
        $msg = date('Y-m-d H:i:s').' '.$line.' '.$msg;
    }
}

Log::write("wuhuu!"); // write new log entry including >>this<< line/filename/..
?>

In former times I used debug_backtrace() or new \Exception + getTrace(). Would it be possible (or easier) to use some great super-special late static binding feature-keywords/functions?


Solution

  • Unfortunately debug_backtrace is probably your best best, although this is quite inefficient.

    The alternative would be to pass the line and file back to your log method...

    Log::write("wuhuu!", __LINE__, __FILE__);
    

    It's a pain in the ass but I can't see another solution.