Get a list of variables in a php file.

This one is easy. Say you want to get a list of variables used in a php file. Then you want to search for these variables in a separate file so you can find any variables that are shared between the files.

First we need to print a unique list of the variables used in the source file. For this we need to create a script (readvars.php) to read the source.php file. readvars.php:


$tk	=	token_get_all(file_get_contents($argv[1]));
$vars	=	array();

foreach($tk as $k)
  if(is_array($k) && $k[0] == T_VARIABLE)
    $vars[]	=	$k[1];

$vars	=	array_unique($vars);

echo join("\\|\\", $vars);

Then execute the php file and make it print the variables from source.php.

user@home> php -f readvars.php path/to/my/source.php

In the above example, it prints a delimited string that I will use to find the variables that are also used in a second.php file. This time I will use grep to find the substrings.

user@home> grep -o "\$var1\|$var2\|\$myvar\|\$varrrrr" second.php 

And now we see that $var1 and $var2 variables (or srings) are found in the source of second.php

Additionally you can search all files in a single directory by using grep -o … *.php