Php 有没有办法找出哪一个文件使用过一次?

Php 有没有办法找出哪一个文件使用过一次?,php,require-once,Php,Require Once,假设我有以下情况: File1.php: <?php require_once('init.php'); ... ?> File2.php: <?php require_once('init.php'); ... ?> init.php: <?php magic_function_which_tells_me_which_file_parsed_this_file(); ... ?> 我知道这很难做到,但是有没有办法从init.php中知道当

假设我有以下情况:

File1.php:

<?php
require_once('init.php');
...
?>

File2.php:

<?php
require_once('init.php');
...
?>

init.php:

<?php
magic_function_which_tells_me_which_file_parsed_this_file();
...
?>


我知道这很难做到,但是有没有办法从init.php中知道当前执行中包含init.php的文件?

您可以使用
debug\u backtrace
找到调用方,即使没有函数:

test1.php

<?php
echo 'test1';
include 'test2.php';

无论如何,我不建议使用它,因为过度使用它会显著降低性能。

在init.php的顶部,您可以使用它来获取有关堆栈的信息。这将告诉您当前文件包含在哪个文件中,以及在哪一行

这是回溯输出的一个示例。如果你把它放在一个函数中,你会有另一层数据。如果您在文件本身中正确地调用它,那么最顶层将告诉您该文件包含的文件

array (size=2)
  0 => 
    array (size=3)
      'file' => string 'fileThatIncudedMe.php' (length=63)
      'line' => int 6
      'function' => string 'require_once' (length=12)
您可以将其包装为一个实用程序函数:

function whoIncludedThisFile() {
    $bt = debug_backtrace();
    $includedMe = false;
    while (count($bt) > 0) {
        $set = array_shift($bt);
        if (
            array_key_exists('function', $set) === true &&
            in_array($set['function'], array('require', 'require_once', 'include', 'include_once'))
        ){
            $includedMe = array('file'=>$set['file'], 'line'=>$set['line']);
            break;
        }
    }
    return $includedMe;
}

print_r(whoIncludedThisFile());
// Array ( [file] => topLevelFile.php [line] => 2 )
当然可以。带着

#0 require_once()在[C:\xampp\htdocs\file2.php:3]处调用

#1在[C:\xampp\htdocs\file1.php:3]调用一次(C:\xampp\htdocs\file2.php)


这将告诉您,
init.php
包含在
file2.php
第3行
3

中。您也可以尝试使用变量来实现这一点。 我们将其命名为$parentFile:

$parentFile = basename(__FILE__);
require('some.file.here.php');
在some.file.here.php中:

if($parentFile == 'another.file.php')
    // do something;

我将插嘴回答——显然,所有的功劳都归于在我之前已经回答过这个问题的人

我所做的是将调试回溯输出格式化到错误日志:

$debug = debug_backtrace(2 , 16);
error_log('-------------------------------' );
foreach ( $debug as $error ) {
     error_log( str_pad( $error['file' ], 120 ) . str_pad($error ['line'] , 8) . $error['function' ] );
}

结果将是每行一个文件,以表格的方式包含(文件、行、函数)。

您这样问是因为您希望在不同的情况下包含不同的代码吗?我认为短语“遗留代码”已经足够了:)我知道使用了init文件,但在此之前我无法跟踪执行情况。我没有看到PHP5.5中缺少这方面的信息——您是否有关于该断言的参考,即它已被删除?文档页面也没有提到这些信息被删除。@ChrisBaker抱歉,我只是在文档上再次读到了这一点,显然我被误导了-我的答案提交得太快了:\OMG,我现在觉得很愚蠢,我故意忽略了debug\u backtrace()因为我认为这只适用于函数。我添加了一个小实用函数来解析回溯数据中的信息,可能会有所帮助:)是的,在某些情况下这是一个很好的方法,但在我的情况下,我不知道父文件,因为我正在处理非常旧的代码。@ChrisBaker你得到了我的投票,这将直接进入一个要点:这很好!如果OP接受你和你之间的答复,我会赞成你的。
if($parentFile == 'another.file.php')
    // do something;
$debug = debug_backtrace(2 , 16);
error_log('-------------------------------' );
foreach ( $debug as $error ) {
     error_log( str_pad( $error['file' ], 120 ) . str_pad($error ['line'] , 8) . $error['function' ] );
}