Coder Perfect

What’s the best way to figure out where a function is defined?

Problem

What is the best way to figure out the file and line a function was defined in?

Asked by foreline

Solution #1

You could also do it directly in PHP:

$reflFunc = new ReflectionFunction('function_name');
print $reflFunc->getFileName() . ':' . $reflFunc->getStartLine();

Answered by Tom Haigh

Solution #2

Use an IDE that allows you to do so (I recommend Eclipse PDT), or grep it if you’re on Linux, or use wingrep. It would look like this in Linux:

grep -R "function funName" *

from within the project’s root folder

Answered by Johnco

Solution #3

If you’re using Netbeans, you can CTRL+Click the function name to go to where it’s defined, as long as the file is in the project folder you specified.

However, there is no code or function to accomplish this.

Answered by Stephen Melrose

Solution #4

I believe you mean “defined” when you say “described.” For this, you’ll need a good IDE that can handle it.

Answered by Anton Gogolev

Solution #5

Using only basic php, here’s a simple function that will scan your entire project files for a given text and tell you which file it’s in and what char point it starts at. I hope this is of assistance to someone…

<?php 
$find="somefunction()";

echo findString('./ProjectFolderOrPath/',$find);

function findString($path,$find){
    $return='';
    ob_start();
    if ($handle = opendir($path)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                if(is_dir($path.'/'.$file)){
                    $sub=findString($path.'/'.$file,$find);
                    if(isset($sub)){
                        echo $sub.PHP_EOL;
                    }
                }else{
                    $ext=substr(strtolower($file),-3);
                    if($ext=='php'){
                        $filesource=file_get_contents($path.'/'.$file);
                        $pos = strpos($filesource, $find);
                        if ($pos === false) {
                            continue;
                        } else {
                            echo "The string '$find' was found in the file '$path/$file and exists at position $pos<br />";
                        }
                    }else{
                        continue;
                    }
                }
            }
        }
        closedir($handle);
    }
    $return = ob_get_contents();
    ob_end_clean();
    return $return;
}
?>

Answered by Lawrence Cherone

Post is based on https://stackoverflow.com/questions/2222142/how-to-find-out-where-a-function-is-defined