tags:

views:

42

answers:

3

Ok, here is a real short query. I am calling __FILE__ from inside a function. Now, this function itself is in a required file.

Now, when I call this function from inside the Parent file, will the __FILE__ output the parent file or the file which was included?

Oh, and I am looking for a source where I can confirm, if possible, because my tests here are giving me entirely absurd results.

Also, if this should display the child (included) file, how should I go about it so that it rather displays the parent filepath? (some variation or something?)

+2  A: 
codaddict
hmm, so anyway to get the parent filepath? I can not use "SCRIPT_FILENAME" since the parent file is also included inside a file..
Stoic
A: 

__FILE__ is always replaced with the filename in which the symbol appears.

To get the name of the file from which a function was called, you can use debug_backtrace(). This returns the current callstack as an array, with each sub-array containing the file, line and function keys from which the call was made.

You can shift the front-most element off the array to get the location from which a function was called:

a.php:

<?php

require_once('b.php');

b();

b.php:

<?php

function b() {
   $bt = debug_backtrace();
   var_export($bt); 
}

output:

array (
  0 => array (
    'file'     => '/home/meagar/a.php',
    'line'     => 5,
    'function' => 'b',
    'args'     => array( ),
  ),
)

The same thing works without function calls:

a.php:

<?php require_once('b.php');

b.php:

<?php
$bt = debug_backtrace();
var_export($bt);

output:

array (
  0 => array (
    'file'     => '/home/meagar/a.php',
    'line'     => 3,
    'function' => 'require_once',
  ),
)
meagar
Won't work if the including file didn't make a function call
Pekka
@Pekka Yes it will, see updated answer.
meagar
A: 

To my knowledge, what you are looking for - getting the path of a "parent" include that in itself again is an include - is not possible, not even using debug_backtrace().

You would have to create your own include function that keeps track of a "stack" of included files.

Pekka