كيفية الحصول على اسم الملف الذي أدرج فئة في PHP
سؤال
وأنا أفهم أن مسألة من الصعب نوعا ما فهم، لم أكن أعرف كيف نطلب بطريقة أفضل، ولذا فإنني سوف تستخدم هذا المثال رمز لجعل الأمور أكثر وضوحا:
إذا كان لدي الملفات التالية:
و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
}
?>
والطبقة / 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;
}
?>
وعلى FILE سحر مستمر ليست صحيحة، فإنها ترجع مسار / إلى / myClass.php
المحلول
وفي حال كنت بحاجة للحصول على "test.php" رؤية $_SERVER['SCRIPT_NAME']
نصائح أخرى
وانتهى بي الأمر باستخدام:
$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_backtrace بعض consenquencies السرعة.
لا تنتمي إلى StackOverflow