PHP fonksiyon / yöntemini çağırarak adını almak nasıl?

7 Cevap

Ben fonksiyonu debug_backtrace farkında değilim, ama GetCallingMethodName() gibi fonksiyon uygulama kullanmak için bazı hazır arıyorum? Çok yöntemin sınıf verdiyse (bu gerçekten bir yöntemi ise) mükemmel olurdu.

Ben (kendim yapmıyorum) umut, normal tembellik alınacak istiyorum, ama iyi programlama tembellik.

EDIT: Here is the answer: http://stackoverflow.com/questions/190421/caller-function-in-php-5/190426#190426

7 Cevap

debug_backtrace() fonksiyonu tembel iseniz size GetCallingMethodName() kendiniz kod gereken bir neden daha var, bu bilmek tek yoludur. Fight the laziness! :D

Basit:

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

Ayrıca php istisna tarafından sağlanan bilgileri kullanarak, zarif bir çözüm:


function GetCallingMethodName(){
    $e = new Exception();
    $trace = $e->getTrace();
    //position 0 would be the line that called this function so we ignore it
    $last_call = $trace[1];
    print_r($last_call);
}

function firstCall($a, $b){
    theCall($a, $b);
}

function theCall($a, $b){
    GetCallingMethodName();
}

firstCall('lucia', 'php');

Ve sen bu olsun ... (voilà!)

Array
(
    [file] => /home/lufigueroa/Desktop/test.php
    [line] => 12
    [function] => theCall
    [args] => Array
        (
            [0] => lucia
            [1] => php
        )

)

Ben sadece "get_caller" olarak adlandırılan bu bir versiyonunu yazdı, ben yardımcı olur umarım. Mine oldukça tembel olduğunu. Sadece bir işlevden get_caller () çalıştırabilir, bunu şöyle belirtmek zorunda değilsiniz:

get_caller(__FUNCTION__);

Burada ilginç bir test durumu ile tam bir senaryo:

<?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 () get_caller () çağırır, kim) (kadın çağırır. kadın () temkinli olduğunu ve bunu söylemedi, bu nedenle öğrenmek için recurses çünkü get_caller (), henüz kimin aradığını bilmiyor. Sonra kadın () kim aradı döndürür. Ve bir tarayıcıda kaynak kod modunda çıktının fonksiyon yığını gösterir:

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.

Ben gördüğüm bu soruya en iyi cevabı:

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

Kısa ve temiz

Ben sadece (bir Magento proje üzerinde çalışan) çağırarak sınıfları / yöntemlerini listelemek için bir şey gerekiyordu.

debug_backtrace yararlı bilgiler ton sağlarken ben arama fonksiyonu and class sadece ilgili olduğu için, bu Magento kurulum için tükürdüler bilgi miktarı (82.000 'den fazla satır!) Ezici oldu Ben bu küçük çözümü çalıştı:

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

Benim için debug_backtrace Benim bellek sınırı vurmak, ve ben onlar ne kadar giriş ve e-posta hataları üretimde kullanmak istedim.

Bunun yerine zekice işler bu çözüm bulundu!

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