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

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

Imagine I have the following situation:

File1.php


Function.php



        
3条回答
  •  隐瞒了意图╮
    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).

提交回复
热议问题