How do I find out which file includes the other in PHP?

Asked

Viewed 586 times

3

I would like to know in PHP how do I find out which is the parent file, in an inclusion, through the child file.

Example:

  • avo.php
  • pai.php
  • php son.

In the archive avo.php I have:

include_once 'pai.php';

And in the archive pai.php I have:

#pai.php
include_once 'filho.php';
  • Through the archive filho.php, how can I discover that it is included by pai.php?
  • How can I find out, atavés de filho.php, that pai.php is included by avo.php?
  • I do not know if there is a native method that does this, but if you need to know who is the "father" to do something dynamized in the child, an alternative would be to overwrite the include function, writing the name of the class that is performing include in a variable, then in the child you have access to this variable and respectively the name.

  • Actually, the goal is to find out where inclusion comes from. I’m in an application where I use filho.php, however I do not know who is the file that includes this class. You understand?

1 answer

3


Use debug_backtrace() or debug_print_backtrace, it can detect both include, require, include_once, require_once, how much scope of functions and classes.

Using debug_backtrace():

  • Filing cabinet /foo/a. php:

    <?php
    function a_test($str)
    {
        echo "\nOlá: $str";
        var_dump(debug_backtrace());
    }
    
    a_test('amigo');
    ?>
    
  • Filing cabinet /foo/b. php:

    <?php
    include_once '/foo/a.php';
    ?>
    
  • Upshot:

    Olá: amigo
    array(2) {
    [0]=>
    array(4) {
        ["file"] => string(10) "/foo/a.php"
        ["line"] => int(10)
        ["function"] => string(6) "a_test"
        ["args"]=>
        array(1) {
          [0] => &string(6) "amigo"
        }
    }
    [1]=>
    array(4) {
        ["file"] => string(10) "/foo/b.php"
        ["line"] => int(2)
        ["args"] =>
        array(1) {
          [0] => string(10) "/foo/a.php"
        }
        ["function"] => string(12) "include_once"
      }
    }
    

Using debug_print_backtrace:

  • Filing cabinet foo.php:

    <?php
    function a() {
        b();
    }
    
    function b() {
        c();
    }
    
    function c(){
        debug_print_backtrace();
    }
    
    a();
    ?>
    
  • Filing cabinet index php.:

    <?php
    include 'foo.php';
    ?>
    
  • Upshot:

    #0  c() called at [/foo.php:10]
    #1  b() called at [/foo.php:6]
    #2  a() called at [/foo.php:17]
    #3  include(/foo.php) called at [/index.php:3]
    
  • 1

    Just to make it sound boring, I’m gonna use it debug_print_backtrace, rsrsrs

  • @Wallacemaxters Just to be another pain in the ass, I edited the answer :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.