Development Tip

PHP에서 현재 함수를 실행하는 코드 줄과 파일을 얻습니까?

yourdevel 2021. 1. 6. 20:28
반응형

PHP에서 현재 함수를 실행하는 코드 줄과 파일을 얻습니까?


다음 상황이 있다고 상상해보십시오.

File1.php

<?php
 include("Function.php");
 log("test");
?>

Function.php

<?php
 function log($msg)
 {
  echo "";
 }
?>

다음을 생성하도록 로그 함수를 변경하고 싶습니다.

test (파일 : File1.php, 줄 번호 : 3)

그렇다면 PHP에서 현재 함수를 실행 한 코드의 파일 이름과 줄 번호를 얻는 방법은 무엇입니까?

백 로그 사용 주석 편집 : 객체 지향 프로그래밍 방식으로 백 로그를 사용하면 다음과 같은 상황이 발생합니다.

Index.php

<?php
 include("Logger.static.php");
 include("TestClass.class.php");
 new TestClass();
?>

TestClass.class.php

<?php
 class TestClass
 {
   function __construct()
   {
     Logger::log("this is a test log message");
   }
 }
?>

Logger.static.php

<?php
 class Logger
 {
   static public function log($msg)
   {
     $bt = debug_backtrace();
     $caller = array_shift($bt);
     echo $caller['file'];
     echo $caller['line'];
   }
 }
?>

이 예제는 "Index.php"파일로 반환되고 4 번 줄에 클래스가 시작됩니다. 그러나 TestClass.class.php 파일과 줄 번호 6을 반환해야합니다.이 문제를 해결하는 방법이 있습니까?


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.    
}

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.


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).

ReferenceURL : https://stackoverflow.com/questions/1252529/get-code-line-and-file-thats-executing-the-current-function-in-php

반응형