Search code examples
phpfunctiondebugging

Finding out the filename that called my function in PHP


How do I find out the filename of the script that called my function?

For example,

function sthing() {
echo __FILE__; // echoes myself
echo __CALLER_FILE__; // echoes the file that called me
}

Solution

  • A solution might be to use the debug_backtrace function : in the backtrace, that kind of information should be present.

    Or, as Gordon pointed out in a comment, you can also use debug_print_backtrace if you just want to output that information and not work with it.


    For instance, with temp.php containing this :

    <?php
    include 'temp-2.php';
    my_function();
    

    and with temp-2.php containing this :

    <?php
    function my_function() {
        var_dump(debug_backtrace());
    }
    


    Calling temp.php (i.e. the first script) from my browser gets me this output :

    array
      0 => 
        array
          'file' => string '/.../temp/temp.php' (length=46)
          'line' => int 5
          'function' => string 'my_function' (length=11)
          'args' => 
            array
              empty
    

    In there, I have the "temp.php" filename -- which is the one in which the function has been called.


    Of course, you'll have to test a bit more (especially in situations where the function is not in the "first level" included file, but in a file included by another one -- not sure debug_backtrace will help much, there...) ; but this might help you get a first idea...