Pim Jager
Pim Jager

Reputation: 32119

Howto get filename from which class was included in PHP

I understand that the question is rather hard to understand, I didn't know how to ask it better, so I'll use this code example to make things more clear:
If I have the following files:

test.php:

<?php
 include('include.php');
 echo myClass::myStaticFunction();
?>

include.php

<?php
 __autoload($classname){
  include_once("class/".$classname.".php"); //normally checking of included file would happen
 }
?>

class/myClass.php

<?php
 class myClass{
  public static function myStaticFunction(){
   //I want this to return test.php, or whatever the filename is of the file that is using this class
   return SOMETHING;
  }
?>

the magic FILE constant is not the correct one, it returns path/to/myClass.php

Upvotes: 2

Views: 4241

Answers (3)

stAn
stAn

Reputation:

I am using

$arr = @debug_backtrace(false);
if (isset($arr))
foreach ($arr as $data)
{
 if (isset($data['file']))
 echo $data['file'];
 // change it to needed depth
}

This way you don't need to modify the file from which your file is included. debug_backtrace might have some speed consenquencies.

Upvotes: 2

Pim Jager
Pim Jager

Reputation: 32119

I ended up using:

$file = basename(strtolower($_SERVER['SCRIPT_NAME']));

Upvotes: 2

Ivan
Ivan

Reputation: 2262

in case you need to get "test.php" see $_SERVER['SCRIPT_NAME']

Upvotes: 4

Related Questions