Hoe de naam van de aanroepfunctie/methode in PHP te krijgen?

Ik ben op de hoogte van de functie debug_backtrace, maar ik ben op zoek naar een gebruiksklare implementatie van een functie zoals GetCallingMethodName()? Het zou perfect zijn als het ook de klasse van de methode zou geven (als het inderdaad een methode is).


Antwoord 1, autoriteit 100%

De eenvoudigste manier is:

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

Antwoord 2, autoriteit 27%

De functie debug_backtrace()is de enige manier om dit te weten. Als je lui bent, is dit nog een reden waarom je de GetCallingMethodName()zelf moet coderen. Vecht tegen de luiheid! 😀


Antwoord 3, autoriteit 10%

Vanaf php 5.4 kunt u gebruik maken van

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

Hiermee wordt geen geheugen verspild omdat het argumenten negeert en alleen de laatste 2 backtrace-stackitems retourneert, en geen meldingen genereert zoals andere antwoorden hier.


Antwoord 4, autoriteit 6%

Je kunt ook de informatie van een php-uitzondering gebruiken, het is een elegante oplossing:

functie GetCallingMethodName(){
  $e = nieuwe uitzondering();
  $trace = $e->getTrace();
  //positie 0 zou de regel zijn die deze functie aanroept, dus we negeren het
  $last_call = $trace[1];
  print_r($last_call);
}
function firstCall($a, $b){
  theCall($a, $b);
}
functie theCall($a, $b){
  GetCallingMethodeNaam();
}
firstCall('lucia', 'php');

En je snapt dit… (voila!)

Array
(
  [bestand] => /home/lufigueroa/Desktop/test.php
  [regel] => 12
  [functie] => de oproep
  [argumenten] => Array
    (
      [0] => lucia
      [1] => php
    )
)

Antwoord 5, autoriteit 4%

Voor mij bereikte debug_backtracemijn geheugenlimiet, en ik wilde dit in de productie gebruiken om fouten te loggen en te e-mailen zodra ze zich voordoen.

In plaats daarvan vond ik deze oplossing die uitstekend werkt!

// 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}"

Antwoord 6, autoriteit 3%

Mijn favoriete manier, in één regel!

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

Je kunt het als volgt gebruiken:

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

Houd er rekening mee dat dit alleen compatibel is met versies van PHP die in het afgelopen jaar zijn uitgebracht. Maar om veiligheidsredenen is het toch een goed idee om je PHP up-to-date te houden.


Antwoord 7, autoriteit 2%

Ik heb zojuist een versie hiervan geschreven met de naam “get_caller”, ik hoop dat het helpt. De mijne is nogal lui. Je kunt get_caller() gewoon uitvoeren vanuit een functie, je hoeft het niet als volgt te specificeren:

get_caller(__FUNCTION__);

Hier is het volledige script met een eigenzinnige testcase:

<?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() roept woman(), die get_caller() aanroept. get_caller() weet nog niet wie het heeft gebeld, omdat de vrouw() voorzichtig was en het niet vertelde, dus het herhaalt zich om erachter te komen. Dan keert het terug wie vrouw() heeft gebeld. En de afdruk in broncodemodus in een browser toont de functiestapel:

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.

Antwoord 8, autoriteit 2%

Ik had iets nodig om de aanroepende klassen/methoden op te sommen (ik werk aan een Magento-project).

Hoewel debug_backtracetonnen nuttige informatie biedt, was de hoeveelheid informatie die het uitspuugde voor de Magento-installatie overweldigend (meer dan 82.000 regels!) Omdat ik me alleen bezighield met de aanroepfunctie en klas, ik heb deze kleine oplossing bedacht:

$callers = debug_backtrace();
foreach( $callers as $call ) {
    echo "<br>" . $call['class'] . '->' . $call['function'];
}

Antwoord 9

De eenvoudigste manier om de naam van de bovenliggende functie te verkrijgen is:

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

Antwoord 10

Het beste antwoord op die vraag dat ik heb gezien is:

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

Kort en duidelijk

Other episodes