PHP에서 함수 / 메소드 호출 이름을 얻는 방법은 무엇입니까? [복제]
이 질문에는 이미 답변이 있습니다.
- PHP에서 호출자 함수의 이름을 얻습니까? 답변 11 개
함수를 알고 debug_backtrace
있지만 함수 구현을 사용할 준비가 되셨 GetCallingMethodName()
습니까? 그것이 메소드의 클래스를 제공한다면 완벽 할 것입니다 (실제로 메소드라면).
debug_backtrace()
기능을 사용하면 게으른 경우에 당신이에게 코딩해야 또 하나의 이유,이 알 수있는 유일한 방법은 GetCallingMethodName()
스스로. 게으름과 싸워라! :디
가장 간단한 방법은 다음과 같습니다.
echo debug_backtrace()[1]['function'];
PHP 5.4부터 사용할 수 있습니다
$dbt=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2);
$caller = isset($dbt[1]['function']) ? $dbt[1]['function'] : null;
인수를 무시하고 마지막 2 개의 역 추적 스택 항목 만 반환하므로 메모리를 낭비하지 않으며 다른 답변으로 통지를 생성하지 않습니다.
PHP 예외에서 제공하는 정보를 사용할 수도 있습니다. 우아한 솔루션입니다.
GetCallingMethodName () 함수 { $ e = 새로운 예외 (); $ trace = $ e-> getTrace (); // 위치 0은이 함수를 호출 한 행이므로 무시합니다. $ last_call = $ trace [1]; print_r ($ last_call); } firstCall ($ a, $ b) 함수 { theCall ($ a, $ b); } theCall ($ a, $ b) { GetCallingMethodName (); } firstCall ( 'lucia', 'php');
그리고 당신은 이것을 얻습니다 ... (voilà!)
정렬 ( [파일] => /home/lufigueroa/Desktop/test.php [라인] => 12 [기능] => theCall [args] => 배열 ( [0] => 루시아 [1] => PHP ) )
내가 좋아하는 방법은 한 줄로!
debug_backtrace()[1]['function'];
다음과 같이 사용할 수 있습니다.
echo 'The calling function: ' . debug_backtrace()[1]['function'];
이것은 작년에 출시 된 PHP 버전과 만 호환됩니다. 그러나 보안상의 이유로 PHP를 최신 상태로 유지하는 것이 좋습니다.
For me debug_backtrace
was hitting my memory limit, and I wanted to use this in production to log and email errors as they happen.
Instead I found this solution which works brilliantly!
// 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}"
I just wrote a version of this called "get_caller", I hope it helps. Mine is pretty lazy. You can just run get_caller() from a function, you don't have to specify it like this:
get_caller(__FUNCTION__);
Here's the script in full with a quirky test case:
<?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() calls woman(), who calls get_caller(). get_caller() doesn't know who called it yet, because the woman() was cautious and didn't tell it, so it recurses to find out. Then it returns who called woman(). And the printout in source-code mode in a browser shows the function stack:
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.
The simplest way of getting parent function name is:
$caller = next(debug_backtrace())['function'];
I needed something to just list the calling classes/methods (working on a Magento project).
While debug_backtrace
provides tons of useful information, the amount of information it spewed out for the Magento installation was overwhelming (over 82,000 lines!) Since I was only concerned with the calling function and class, I worked this little solution up:
$callers = debug_backtrace();
foreach( $callers as $call ) {
echo "<br>" . $call['class'] . '->' . $call['function'];
}
Best answer of that question I've seen is:
list(, $caller) = debug_backtrace(false);
Short and clean
참고URL : https://stackoverflow.com/questions/2110732/how-to-get-name-of-calling-function-method-in-php
'IT story' 카테고리의 다른 글
라 라벨 설치 : ~ / .composer / vendor / bin 디렉토리를 PATH에 배치하는 방법? (0) | 2020.05.09 |
---|---|
Javascript의 객체에서 빈 속성 제거 (0) | 2020.05.09 |
영숫자 텍스트에서 선행 0을 제거하는 방법? (0) | 2020.05.09 |
파이썬 : 설정할 목록을 추가 하시겠습니까? (0) | 2020.05.09 |
특정 경도와 위도로 Google지도에 연결하려면 어떻게해야하나요? (0) | 2020.05.09 |