257

我知道功能debug_backtrace,但我正在寻找一些现成的功能实现,比如GetCallingMethodName()?如果它也给出方法的类(如果它确实是一个方法),那将是完美的。

4

10 回答 10

607

最简单的方法是:

echo debug_backtrace()[1]['function'];
于 2012-06-28T04:24:57.763 回答
163

debug_backtrace()函数是了解这一点的唯一方法,如果你很懒,这是你应该GetCallingMethodName()自己编写代码的另一个原因。与懒惰作斗争!:D

于 2010-01-21T16:13:12.160 回答
64

从 php 5.4 开始,您可以使用

        $dbt=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2);
        $caller = isset($dbt[1]['function']) ? $dbt[1]['function'] : null;

这不会浪费内存,因为它忽略参数并仅返回最后 2 个回溯堆栈条目,并且不会在此处生成通知作为其他答案。

于 2015-02-19T09:02:20.890 回答
34

您还可以使用 php 异常提供的信息,这是一个优雅的解决方案:

函数GetCallingMethodName(){
    $e = 新异常();
    $trace = $e->getTrace();
    //位置 0 将是调用此函数的行,因此我们忽略它
    $last_call = $trace[1];
    print_r($last_call);
}

函数 firstCall($a, $b){
    呼叫($a,$b);
}

函数调用($a,$b){
    GetCallingMethodName();
}

firstCall('lucia', 'php');

你得到这个......(瞧!)

大批
(
    [文件] => /home/lufigueroa/Desktop/test.php
    [行] => 12
    [功能] => theCall
    [参数] => 数组
        (
            [0] => 露西亚
            [1] => php
        )

)
于 2012-02-03T18:50:42.190 回答
26

对我来说debug_backtrace,我的内存已经达到了极限,我想在生产中使用它来记录和发送错误发生时的电子邮件。

相反,我发现这个解决方案非常有效!

// Make a new exception at the point you want to trace, and trace it!
$e = new Exception;
var_dump($e->getTraceAsString());

// Outputs the following 
#2 /usr/share/php/PHPUnit/Framework/TestCase.php(626): SeriesHelperTest->setUp()
#3 /usr/share/php/PHPUnit/Framework/TestResult.php(666): PHPUnit_Framework_TestCase->runBare()
#4 /usr/share/php/PHPUnit/Framework/TestCase.php(576): PHPUnit_Framework_TestResult->run(Object(SeriesHelperTest))
#5 /usr/share/php/PHPUnit/Framework/TestSuite.php(757): PHPUnit_Framework_TestCase->run(Object(PHPUnit_Framework_TestResult))
#6 /usr/share/php/PHPUnit/Framework/TestSuite.php(733): PHPUnit_Framework_TestSuite->runTest(Object(SeriesHelperTest), Object(PHPUnit_Framework_TestResult))
#7 /usr/share/php/PHPUnit/TextUI/TestRunner.php(305): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult), false, Array, Array, false)
#8 /usr/share/php/PHPUnit/TextUI/Command.php(188): PHPUnit_TextUI_TestRunner->doRun(Object(PHPUnit_Framework_TestSuite), Array)
#9 /usr/share/php/PHPUnit/TextUI/Command.php(129): PHPUnit_TextUI_Command->run(Array, true)
#10 /usr/bin/phpunit(53): PHPUnit_TextUI_Command::main()
#11 {main}"
于 2014-02-27T10:53:15.377 回答
21

我最喜欢的方式,在一条线上!

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

你可以像这样使用它:

echo 'The calling function: ' . debug_backtrace()[1]['function'];

请注意,这仅与去年发布的 PHP 版本兼容。但是出于安全原因,让您的 PHP 保持最新是一个好主意。

于 2014-10-11T20:10:41.593 回答
13

我刚刚写了一个名为“get_caller”的版本,希望对您有所帮助。我的很懒。你可以从一个函数中运行 get_caller() ,你不必像这样指定它:

get_caller(__FUNCTION__);

这是带有一个古怪测试用例的完整脚本:

<?php

/* This function will return the name string of the function that called $function. To return the
    caller of your function, either call get_caller(), or get_caller(__FUNCTION__).
*/
function get_caller($function = NULL, $use_stack = NULL) {
    if ( is_array($use_stack) ) {
        // If a function stack has been provided, used that.
        $stack = $use_stack;
    } else {
        // Otherwise create a fresh one.
        $stack = debug_backtrace();
        echo "\nPrintout of Function Stack: \n\n";
        print_r($stack);
        echo "\n";
    }

    if ($function == NULL) {
        // We need $function to be a function name to retrieve its caller. If it is omitted, then
        // we need to first find what function called get_caller(), and substitute that as the
        // default $function. Remember that invoking get_caller() recursively will add another
        // instance of it to the function stack, so tell get_caller() to use the current stack.
        $function = get_caller(__FUNCTION__, $stack);
    }

    if ( is_string($function) && $function != "" ) {
        // If we are given a function name as a string, go through the function stack and find
        // it's caller.
        for ($i = 0; $i < count($stack); $i++) {
            $curr_function = $stack[$i];
            // Make sure that a caller exists, a function being called within the main script
            // won't have a caller.
            if ( $curr_function["function"] == $function && ($i + 1) < count($stack) ) {
                return $stack[$i + 1]["function"];
            }
        }
    }

    // At this stage, no caller has been found, bummer.
    return "";
}

// TEST CASE

function woman() {
    $caller = get_caller(); // No need for get_caller(__FUNCTION__) here
    if ($caller != "") {
        echo $caller , "() called " , __FUNCTION__ , "(). No surprises there.\n";
    } else {
        echo "no-one called ", __FUNCTION__, "()\n";
    }
}

function man() {
    // Call the woman.
    woman();
}

// Don't keep him waiting
man();

// Try this to see what happens when there is no caller (function called from main script)
//woman();

?>

man() 调用 woman(),后者调用 get_caller()。get_caller() 还不知道是谁调用的,因为 woman() 很谨慎,没有告诉它,所以它递归查找。然后它返回谁调用了woman()。浏览器中源代码模式的打印输出显示了函数堆栈:

Printout of Function Stack: 

Array
(
    [0] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 46
            [function] => get_caller
            [args] => Array
                (
                )

        )

    [1] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 56
            [function] => woman
            [args] => Array
                (
                )

        )

    [2] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 60
            [function] => man
            [args] => Array
                (
                )

        )

)

man() called woman(). No surprises there.
于 2011-01-22T12:17:15.703 回答
12

我需要一些东西来列出调用类/方法(在 Magento 项目上工作)。

虽然debug_backtrace提供了大量有用的信息,但它为 Magento 安装提供的信息量是压倒性的(超过 82,000 行!)因为我只关心调用函数类,所以我设计了这个小解决方案:

$callers = debug_backtrace();
foreach( $callers as $call ) {
    echo "<br>" . $call['class'] . '->' . $call['function'];
}
于 2013-06-20T18:07:59.313 回答
5

获取父函数名称的最简单方法是:

$caller = next(debug_backtrace())['function'];
于 2014-05-23T11:15:54.090 回答
1

我见过的这个问题的最佳答案是:

list(, $caller) = debug_backtrace(false);

短而干净

于 2012-12-11T10:15:43.443 回答