0

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?

NaN
  • 3,501
  • 8
  • 44
  • 77

3 Answers3

1

Yea,

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are eight magical constants that change depending on where they are used. For example, the value of LINE depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows:

_LINE_, _CLASS_, _METHOD_, etc

http://php.net/manual/en/language.constants.predefined.php

But you still need give that data to the method like log(_LINE_,_METHOD_).

for global warnings you can catch those with http://www.php.net/manual/en/function.set-error-handler.php

other then that ..

  • AFAIK: these functions do not have anything in common with **late static binding** and would return the information about the logging-function itself and not the line/function/class the function gets called! ... – NaN Aug 21 '12 at 13:26
  • 1
    yea, but you dont have any other option then Log::write("wuhuu!", __LINE__, __METHOD__ );. the only other option you have is debug_backtrace – Mient-jan Stelling Aug 21 '12 at 13:35
  • take a look @ http://stackoverflow.com/questions/1513069/how-can-i-get-the-callee-in-php same problem same solution :) – Mient-jan Stelling Aug 21 '12 at 13:36
  • ok, but the is is from 2009 - there where many innovations and my question was "is it possible with late static binding" and not are there any old/bulky alternatives. – NaN Aug 21 '12 at 13:45
1

You should check the XDebug extension:

xdebug_call_file(), xdebug_call_line(), xdebug_call_class(), xdebug_call_function()

These kind of function (XDebug, debug_backtrace()) are not recommended in a production environment.

Peter Kiss
  • 9,309
  • 2
  • 23
  • 38
  • but xdebug is an extension - It wouldn't be an opinion to install an additional extension *just* for logging. – NaN Aug 21 '12 at 13:22
1

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.

fire
  • 21,383
  • 17
  • 79
  • 114