PHPの関数がどこから呼び出されたかを調べる方法はありますか? 例:
function epic()
{
fail();
}
function fail()
{
//at this point, how do i know, that epic() has called this function?
}
PHPの関数がどこから呼び出されたかを調べる方法はありますか? 例:
function epic()
{
fail();
}
function fail()
{
//at this point, how do i know, that epic() has called this function?
}
使用できますdebug_backtrace()。
例:
<?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()...
}
}
それでも本当に方法がわからない場合は、ここに解決策があります:
$backtrace = debug_backtrace();
echo 'Mu name is '.$backtrace[1]['function'].', and I have called him! Muahahah!';
debug_backtrace 関数を使用します: http://php.net/manual/en/function.debug-backtrace.php
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 の外にある場合、サーバーがそれを許可しないようにセットアップされるため、見つけることができません。1 フォルダーの深さでのみテストしましたが、再帰的な方法論は理論的には機能するはずです。
これはバージョン 0.1 のようなものですが、開発を続けるつもりはないので、誰かが更新した場合は自由に再投稿してください。