在 PHP 中获取调用函数的名称?

是否有一个 PHP 函数来查找给定函数中调用者函数的名称?

88435 次浏览

debug_backtrace() 提供当前调用堆栈中的参数、函数/方法调用的详细信息。

查看 Debug _ backtrace-这可以跟踪您的呼叫堆栈所有的方式到顶部。

接听电话的方法如下:

$trace = debug_backtrace();
$caller = $trace[1];


echo "Called by {$caller['function']}";
if (isset($caller['class']))
echo " in {$caller['class']}";

您可以从 Debug _ backtrace返回的数组中提取此信息

Xdebug 提供了一些很好的函数。

<?php
Class MyClass
{
function __construct(){
$this->callee();
}
function callee() {
echo sprintf("callee() called @ %s: %s from %s::%s",
xdebug_call_file(),
xdebug_call_line(),
xdebug_call_class(),
xdebug_call_function()
);
}
}
$rollDebug = new MyClass();
?>

会返回痕迹

callee() called @ /var/www/xd.php: 16 from MyClass::__construct

在 ubuntu 上安装 Xdebug 的最佳方法是

sudo aptitude install php5-xdebug

您可能需要首先安装 php5-dev

sudo aptitude install php5-dev

更多信息

做了这个,我自己也用这个

/**
* Gets the caller of the function where this function is called from
* @param string what to return? (Leave empty to get all, or specify: "class", "function", "line", "class", etc.) - options see: http://php.net/manual/en/function.debug-backtrace.php
*/
function getCaller($what = NULL)
{
$trace = debug_backtrace();
$previousCall = $trace[2]; // 0 is this call, 1 is call in previous function, 2 is caller of that function


if(isset($what))
{
return $previousCall[$what];
}
else
{
return $previousCall;
}
}

这已经很晚了,但是我想共享一个函数,它将给出调用当前函数的函数的名称。

public function getCallingFunctionName($completeTrace=false)
{
$trace=debug_backtrace();
if($completeTrace)
{
$str = '';
foreach($trace as $caller)
{
$str .= " -- Called by {$caller['function']}";
if (isset($caller['class']))
$str .= " From Class {$caller['class']}";
}
}
else
{
$caller=$trace[2];
$str = "Called by {$caller['function']}";
if (isset($caller['class']))
$str .= " From Class {$caller['class']}";
}
return $str;
}

我希望这会有用。

这个对我来说效果最好: var_dump(debug_backtrace());

实际上,我认为 debug _ print _ backtrace ()可以满足您的需要。 Http://php.net/manual/en/function.debug-print-backtrace.php

echo debug_backtrace()[1]['function'];

PHP 5.4开始工作。

或者优化(例如,对于非调试用例) :

echo debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'];

第一个参数防止填充未使用的函数参数,第二个参数将跟踪限制为两个级别(我们需要第二个级别)。

我只是想说 Flori 的方法不能作为函数使用,因为它总是返回被调用的函数名,而不是调用者,但我没有注释的名声。我根据 Flori 的回答做了一个非常简单的函数,对我的情况很有用:

class basicFunctions{


public function getCallerFunction(){
return debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function'];
}


}

例子:

function a($authorisedFunctionsList = array("b")){
$ref = new basicFunctions;
$caller = $ref->getCallerFunction();


if(in_array($caller,$authorisedFunctionsList)):
echo "Welcome!";
return true;
else:
echo "Unauthorised caller!";
return false;
endif;
}


function b(){
$executionContinues = $this->a();
$executionContinues or exit;


//Do something else..
}

这应该会奏效:

$caller = next(debug_backtrace())['function'];

这样就很好了:


// Outputs an easy to read call trace
// Credit: https://www.php.net/manual/en/function.debug-backtrace.php#112238
// Gist: https://gist.github.com/UVLabs/692e542d3b53e079d36bc53b4ea20a4b


Class MyClass{


public function generateCallTrace()
{
$e = new Exception();
$trace = explode("\n", $e->getTraceAsString());
// reverse array to make steps line up chronologically
$trace = array_reverse($trace);
array_shift($trace); // remove {main}
array_pop($trace); // remove call to this method
$length = count($trace);
$result = array();
   

for ($i = 0; $i < $length; $i++)
{
$result[] = ($i + 1)  . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
}
   

return "\t" . implode("\n\t", $result);
}


}


// call function where needed to output call trace


/**
Example output:
1) /var/www/test/test.php(15): SomeClass->__construct()
2) /var/www/test/SomeClass.class.php(36): SomeClass->callSomething()
**/```

我创建了一个泛型类,对于希望以用户可读的方式查看调用方法的跟踪的许多人来说,这个类都很有帮助。在我的一个项目中,我们需要记录这些信息。

use ReflectionClass;


class DebugUtils
{
/**
* Generates debug traces in user readable form
*
* @param integer $steps
* @param boolean $skipFirstEntry
* @param boolean $withoutNamespaces
* @return string
*/
public static function getReadableBackTracke(
$steps = 4,
$skipFirstEntry = true,
$withoutNamespaces = true
) {
$str = '';
try {
$backtrace = debug_backtrace(false, $steps);


// Removing first array entry
// to make sure getReadableBackTracke() method doesn't gets displayed
if ($skipFirstEntry)
array_shift($backtrace);


// Reserved, so it gets displayed in calling order
$backtrace = array_reverse($backtrace);


foreach ($backtrace as $caller) {
if ($str) {
$str .= ' --> ';
}
if (isset($caller['class'])) {
$class = $caller['class'];
if ($withoutNamespaces) {
$class = (new ReflectionClass($class))->getShortName();
}
$str .= $class . $caller['type'];
}
$str .= $caller['function'];
}
} catch (\Throwable $th) {
return null;
}


return $str;
}
}

用法: DebugUtils::getReadableBackTracke()

输出样本:

SomeClass->method1 --> SomeOtherClass->method2 --> TargetClass->targetMethod

做好事,不断帮助别人,快乐编码:)