Identifying function usage in PHP code

Its important for programmers to be able to quickly identify all usage of a function. Knowing where and how a function is called helps greatly in understanding the intent of the code and allows the programmer to refactor with confidence.

There aren’t any tools for PHP that identify function usage, the way one might do with Java using Eclipse. The recent release of Zend 6 for Eclipse comes closer with its refactor feature, but only refactors within a single file and not across a project.

I solve this need with a handy grep call. The following grep finds all usage and definitions of a PHP function, and omits results from .svn directories. Just replace FUNC_NAME with the name of the function you’re investigating.

Command line usage

grep -rinE "(function[[:space:]]+|[[:space:]]*::[[:space:]]*|\->|[[:space:]]+)FUNC_NAME[[:space:]]*\(" * | grep -v "/.svn/"

Human readable explanation of the grep syntax

grep -rinE "(
    function[[:space:]]+ |              # match function or method definition
    [[:space:]]*::[[:space:]]* |        # match static method call
    \->|                                # match instance method call
    [[:space:]]+ |                      # match procedural function call
    ,+ |
    )FUNC_NAME[[:space:]]*\(" * |       # SEARCH TERM
    grep -v "/.svn/"                    # omit svn directories

Even more convenient

For the ultimate in grepping convenience (thanks Mike Luton for the tip), copy the following into an executable file in your $PATH:

grep -rinE "(function[[:space:]]+|[[:space:]]*::[[:space:]]*|\->|[[:space:]]+|,+)$1[[:space:]]*\(" * | grep -v "/.svn/"

Name the file “grepf” and call it like so:

grepf some_function_name

2 thoughts on “Identifying function usage in PHP code”

  1. Hey Mariano,

    Just one gotcha I wanted to mention about this. Grep will not match across multiple lines. Something like this would get completely missed by grepf:
    ILikeToUseReturnALot ( $variable

    Also, for things that grepf does match, you may want to include -A 2 -B 2 along with the other parameters for grep. It will give you the two lines above and below the matching line which may contain comments or other parameters not included on the matching line which could give additional contextual help.

  2. In Eclipse I just do a search over the whole project (Ctrl+H) if I wanna see where a method/function is used. After a first search all following searches are usually pretty fast even on projects with several thousand files.

    But I am really disappointed, that it is 2009, and I still haven’t seen an IDE, that allows the development and refactoring features for PHP, that Java developers can use with Eclipse for maaany years now. PHPEclipse is ok, but still far from Eclipse’s Java development capabilities.


Leave a Reply to T. Cancel reply

Your email address will not be published. Required fields are marked *