Get code line and file that's executing the current function in PHP?

前端 未结 3 838
再見小時候
再見小時候 2020-12-04 19:17

Imagine I have the following situation:

File1.php


Function.php



        
相关标签:
3条回答
  • 2020-12-04 19:18

    You can use debug_backtrace().

    http://us3.php.net/manual/en/function.debug-backtrace.php

    So, in your log function, you would be able to retrieve the filename and line number from which the log function was called.

    I'm using this approach in my logging classes and it has significantly reduced the amount of code required to get meaningful log data. Another benefit would be readability. Magic constants tend to get quite ugly when mixed with strings.

    Here's a quick example:

    function log($msg)
    {
      $bt = debug_backtrace();
      $caller = array_shift($bt);
    
      // echo $caller['file'];
      // echo $caller['line'];
    
      // do your logging stuff here.    
    }
    
    0 讨论(0)
  • 2020-12-04 19:23

    This is an old question but seeing as how my solution is not here, I'll provide it for posterity

         try{
            throw new Exception();
        }catch ( Exception $e ){
            $trace = $e->getTrace();
        }
    
        $length = 0;
    
        foreach ($trace as $t){
            if( $t['file'] != __FILE__ ){
                break;
            }
            ++$length;
        }
        return array_slice( $trace, ($length - count( $trace ) ));
    

    You can throw/catch to get a clean stack trace, then you need to look for the first line that contains this file ( typically that is where it is called from ) you can also use the index of the trace if you know it, or the function.

    The exception stack trace is pretty much the same as doing debug_backtrace(true).

    0 讨论(0)
  • 2020-12-04 19:39

    debug_backtrace() can be used to trace back through the call stack. It can be slow though, so be careful with it if you're doing a lot of logging.

    If you're using PHP 5.3, you could take advantage of late static binding and have a base class method of log(), and your child classes could call it but still maintain static references to __FILE__ and __LINE__.

    A final option would be just pass __FILE__ and __LINE__ in as parameters when you call your log() function.

    0 讨论(0)
提交回复
热议问题