Stan
Stan

Reputation: 251

Find declaration of a global variable in PHP

Is there a quick and concise way of finding the declaration of a global variable in PHP?

If we are dealing with a large codebase where the global variable may be referenced in many different files:

Is there any tool/vim plugin/etc that will tell you exactly where the global is being declared for the first time?


Update: I guess you could set a watch breakpoint and look for the first access to the variable. Unfortunately, this type of breakpoint is not yet supported in Xdebug, so for my particular setup, it wouldn't work.

Upvotes: 4

Views: 2297

Answers (2)

Matt
Matt

Reputation: 754

There doesn't need to be any declaration beyond the global $foo declarations you are finding. These do declare the global variable. It can easily be the case that the global variable is only referenced from within these functions.

The following code works, for example:

function print_it() {
    global $my_global;
    echo $my_global;
}
function set_it() {
    global $my_global;
    $my_global = 17;
}
set_it();
print_it();  // echos 17

Upvotes: 0

ale
ale

Reputation: 11824

Are you a Unix-based OS?

I usually do something like grep -rn 'global $myvar' .

in the top-level directory. This does a recursive search of files in the current directory for the declaration.

Or, if you want to get fancy you can search for only PHP files:

grep -rn --include '*.php' 'global $myvar' .

Upvotes: 3

Related Questions