Cam
Cam

Reputation: 15234

Find out where a function comes from?

From time to time, I'm handed bloated, undocumented, buggy PHP code to fix. I have several tools I use to fix such code as quickly as possible.

One thing I'm not sure how to do that occasionally causes me grief is finding where a function is located (in which file it is defined). Note that I don't want to know where a function is called from.

For example I'd like to be able to do this:

//file1.php
function foo(){
    echo 'bar';
}

.

//file2.php
where_is_function('foo');//error
include('file1.php');
echo where_is_function('foo');//outputs'file1.php'

Upvotes: 3

Views: 1989

Answers (3)

mwhite
mwhite

Reputation: 2111

Try this:

function getFunctionLocation($fname) {  
    $includeFilesString = implode(" ", get_included_files());  
    return system("grep 'function $fname' $includeFilesString -l");          
}

But if it's only for development purposes, which it should be, then just run

grep -r "function functionName" *

from the base directory

Upvotes: 2

jeffcook2150
jeffcook2150

Reputation: 4216

grep or grep-like tools. I prefer ack, which makes the output much easier to read and ignores version-control files by default. I highly prefer these tools to constraining myself to code in a bloated, click-hogging IDE. Finding things this way has always worked better than things like Eclipse for me anyway.

To use grep, you would cd to the base directory and then recursively grep the contents of the directory for the function name, possibly including the keywords to define a function. Like this:

cd project/
grep -Rn "def wallace(" .

Ack is like:

cd project/
ack "def wallace("

Upvotes: 3

Ben Rowe
Ben Rowe

Reputation: 28711

Get yourself a good IDE such as netbeans or eclipse. They have functionality to find function declarations, and also find the usages of those functions (under refactoring).

Personally I use netbeans. I simply have to ctrl-click on a function name & netbeans will find where the function is defined, and automatically open the file for me.

Upvotes: 10

Related Questions