programing

php: 함수가 호출된 위치를 확인합니다.

firstcheck 2022. 10. 28. 21:28
반응형

php: 함수가 호출된 위치를 확인합니다.

PHP의 함수가 어디서 호출되었는지 알 수 있는 방법이 있습니까?예:

function epic()
{
  fail();
}

function fail()
{
  //at this point, how do i know, that epic() has called this function?
}

를 사용할 수 있습니다.

예:

<?php

function epic( $a, $b )
{
    fail( $a . ' ' . $b );
}

function fail( $string )
{
    $backtrace = debug_backtrace();

    print_r( $backtrace );
}

epic( 'Hello', 'World' );

출력:

Array
(
    [0] => Array
        (
            [file] => /Users/romac/Desktop/test.php
            [line] => 5
            [function] => fail
            [args] => Array
                (
                    [0] => Hello World
                )

        )

    [1] => Array
        (
            [file] => /Users/romac/Desktop/test.php
            [line] => 15
            [function] => epic
            [args] => Array
                (
                    [0] => Hello
                    [1] => World
                )

        )

)

사용방법:

function fail()
{
    $backtrace = debug_backtrace();

    // Here, $backtrace[0] points to fail(), so we'll look in $backtrace[1] instead
    if (isset($backtrace[1]['function']) && $backtrace[1]['function'] == 'epic')
    {
        // Called by epic()...
    }
}

가장 빠르고 심플한 솔루션

public function func() { //function whose call file you want to find
    $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
}

$trace: Array
(
    [0] => Array
        (
            [file] => C:\wamp\www\index.php
            [line] => 56
            [function] => func
            [class] => (func Class namespace)
            [type] => ->
        )

)

Lenovo 노트북 속도 테스트:인텔 Pentiom CPU N3530 2.16GHz, RAM 8GB

global $times;
$start = microtime(true);
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
$times[] = microtime(true) - $start;

결과:

count($times):  97
min:    2.6941299438477E-5
max:   10.68115234375E-5
avg:    3.3095939872191E-5
median: 3.0517578125E-5
sum:  321.03061676025E-5

the same results with notation without E-5
count($times):  97
min:    0.000026941299438477
max:    0.0001068115234375
avg:    0.000033095939872191
median: 0.000030517578125
sum:    0.0032103061676025

아직 그 방법을 모르는 경우는, 다음과 같은 해결책이 있습니다.

$backtrace = debug_backtrace();
echo 'Mu name is '.$backtrace[1]['function'].', and I have called him! Muahahah!';

아래 코드를 사용해 보십시오.

foreach(debug_backtrace() as $t) {              
   echo $t['file'] . ' line ' . $t['line'] . ' calls ' . $t['function'] . "()<br/>";
}

debug_backtrace 함수를 사용합니다.http://php.net/manual/en/function.debug-backtrace.php

스택의 상부에 있는 콜의 정확한 발신지를 추적하려면 , 다음의 코드를 사용합니다.

$call_origin = end(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));

그러면 체인된 함수는 무시되고 가장 관련성이 높은 콜 정보만 취득됩니다(관련 정보는 무엇을 달성하려고 하는가에 따라 다르기 때문에 느슨하게 사용됩니다.

function findFunction($function, $inputDirectory=""){
    //version 0.1
    $docRoot = getenv("DOCUMENT_ROOT");
    $folderArray = null;
    $dirArray = null;

    // open directory
    $directory = opendir($docRoot.$inputDirectory);

    // get each entry
    while($entryName = readdir($directory)) {
        if(is_dir($entryName) && $entryName != "." && $entryName != ".."){
            $folderArray[] = str_replace($inputDirectory, "", $entryName);
        }
        $ext = explode(".", $entryName);
        if(!empty($ext[1])){
            $dirArray[] = $docRoot.$inputDirectory."/".$entryName;
        }
    }

    // close directory
    closedir($directory);
    $found = false;

    if(is_array($dirArray)){
        foreach($dirArray as $current){
            $myFile = file_get_contents($current);
            $myFile = str_replace("<?php", "", $myFile);
            $myFile = str_replace("?>", "", $myFile);
            if(preg_match("/function ".$function."/", $myFile)){
                $found = true;
                $foundLocation = $current;
                break;
            }
        }
    }
    if($found){
        echo $foundLocation;
        exit;
    } else if(is_array($folderArray)){
        foreach($folderArray as $folder){
            if(!isset($return)){
                $return = findFunction($function, $inputDirectory."/".$folder);
            } else if($return == false){
                $return = findFunction($function, $inputDirectory."/".$folder);
            }
        }
    } else {
        return false;
    }
}

findFunction("testFunction", "rootDirectory");

도움이 됐으면 좋겠네요실제 함수가 httpdocs 외부에 있는 경우 서버가 이를 허용하지 않도록 설정되므로 찾을 수 없습니다.한 폴더 깊이만 테스트했지만 재귀적 방법론은 이론적으로 효과가 있을 것입니다.

이것은 버전 0.1과 비슷하지만, 저는 개발을 계속할 생각이 없기 때문에 누군가 업데이트를 하면 자유롭게 다시 게시할 수 있습니다.

언급URL : https://stackoverflow.com/questions/2960805/php-determine-where-function-was-called-from

반응형