如何获取调用函数的脚本名称?

How to get the name of the script calling a function?

我想编写一个非常通用的日志记录函数:

function msglog($type, $message) {
echo date("r") . " " . __FILE__ . " - $type - $message" . PHP_EOL;
}

我将在我的代码中几乎所有地方使用它,这些代码将在几个 php 脚本 include 中分发。如此处所示,无论在何处调用该函数,__FILE__ 始终使用主脚本文件名赋值。

有没有一种方法可以在函数本身中获取调用脚本的名称,而不必将其作为参数传递?

EDIT1 - 它不是重复的

虽然目的是获取来电信息,但和其他一些问题一样,解决方法也是一样的。知道答案就很明显他们是有联系的。我的问题还有一个 "scope"。它与包含和脚本文件名检索有关,而不是未知上下文中的函数名。

EDIT2 - 答案

是的,debug_backtrace() 函数就是答案。

这是我一直在寻找的解决方案:

function msglog( $type, $message) {
    $caller = debug_backtrace();
    echo date("r") . $caller[0]["file"] . " - $type - $message" . PHP_EOL;
}

尝试:

$caller = debug_backtrace();
$caller = $caller[1];
echo $caller['function'];

您应该得到最后调用的函数的名称

function msglog($type, $message) {
    $caller = debug_backtrace();
    $caller = $caller[1];
    echo date("r") . " " . $caller['function'] . " - $type - $message" . PHP_EOL;
}

您还可以获得其他信息:

"file" => (string) "caller_filename.php"
"line" => (int) number of line in caller_filename.php
"function" => (string) "function name"

使用$_SERVER数组,像这样:

echo date("r") . " " . $_SERVER['PHP_SELF'] . " - $type - $message" . PHP_EOL;

这将始终为您提供调用该函数的文件的名称