如何获取PHP中包含的类的文件名
我知道这个问题很难理解,我不知道如何更好地提问,所以我将使用这个代码示例来让事情更清楚:如何获取PHP中包含的类的文件名,php,include,filenames,Php,Include,Filenames,我知道这个问题很难理解,我不知道如何更好地提问,所以我将使用这个代码示例来让事情更清楚: 如果我有以下文件: test.php: <?php include('include.php'); echo myClass::myStaticFunction(); ?> include.php <?php __autoload($classname){ include_once("class/".$classname.".php"); //normally checki
如果我有以下文件: 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;
}
?>
magic FILE常量不正确,它返回path/to/myClass.php以防需要获取“test.php”请参见$\u SERVER['SCRIPT\u NAME']
我最终使用了:
<?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;
}
?>
$file = basename(strtolower($_SERVER['SCRIPT_NAME']));
我正在使用
$arr = @debug_backtrace(false);
if (isset($arr))
foreach ($arr as $data)
{
if (isset($data['file']))
echo $data['file'];
// change it to needed depth
}
这样,您就不需要修改包含您的文件的文件。debug\u backtrace可能有一些速度问题 再次阅读问题:“magic FILE常量不是正确的,它返回path/to/myClass.php”因此,如果您现在使用脚本C,其中包括一个包含第一个示例(a)的文件,然后您的示例包含自动加载的第二个文件,文件(B),您将使用错误的文件名。是的,好的,这是正确的。然而,在我的情况下,这不是一个问题,因为我总是需要第一个文件(C),我不得不问:你为什么要做这样的事情?这违反了编写良好代码的所有可能规则。如果您确实需要知道文件名,请将其作为函数的参数传递:
MyClass:myStaticFunction(\uuu file\uuu)代码>。感谢您提供的出色的调试回溯,它就像java在调试中一样令人难以置信!