PHP output from __FILE__ file inside included file

Ok, here is a real short request. I am __FILE__ from within a function. Now this function is in the required file.

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

Oh, and I'm looking for a source where I can confirm, if possible, because my tests here give me completely absurd results.

In addition, if in this case the child (included) file should be displayed, how can I do this so that it most likely displays the parent path to the file? (some options or something?)

+4
source share
4 answers

__FILE__ always replaced by the name of the file in which the symbol appears.

To get the name of the file from which the function was called, you can use debug_backtrace() . This returns the current column as an array, with each auxiliary array containing the files, rows, and function keys from which the call was made.

You can drag the front element from the array to get the location from which the function is 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', ), ) 
+3
source

The document says:

__ FILE __
Full path and file name. If used inside include, the name of the bundled file is returned.

+2
source

Here is an example of how I fixed this in one of my projects.

Problem. I had the following method that I called in the head section of my html template:

 public static function loadPageSpecificStyle() { $directory_files = scandir(dirname(__FILE__)); foreach($directory_files as $key => $file_name) { if(strpos($file_name, 'css') !== FALSE) { echo '<link rel="stylesheet" type="text/css" href="' . $file_name . '" />'; } } } 

Decision. I passed the __FILE__ constant as an argument:

 public static function loadPageSpecificStyle($file_as_argument) { $directory_files = scandir(dirname($file_as_argument)); foreach($directory_files as $key => $file_name) { if(strpos($file_name, 'css') !== FALSE) { echo '<link rel="stylesheet" type="text/css" href="' . $file_name . '" />'; } } } 

In the head my page, I then simply call this: WhateverClass::loadPageSpecificStyle(__FILE__);

Hope this helps!

0
source

As far as I know, what you are looking for - getting the path to the "parent" includes what is include in itself again - is impossible without even using debug_backtrace() .

You will need to create your own include function, which tracks the "stack" of included files.

-1
source

All Articles