public
Created

Find Unset Local Variables

  • Download Gist
find-local-vars.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
<?php
 
$path_to_file = '...';
 
$file = explode( "\n", file_get_contents( $path_to_file ) );
 
// Finds local variables that are undeclared.
//
// Doesn't understand foreach() variables, dockblocks, sprintf arguments,
// variables returned by reference from a function like preg_match() or parse_str(),
// assignments that don't start a line, and a few other things.
 
$set_variables = array();
 
foreach ( $file as $num => $line ) {
if ( 0 === strpos( $line, 'function ' ) || $line === '}' ) {
if ( $line === '}' && $found )
echo "----------------------------\n\n";
 
$found = false;
$set_variables = array( '$_POST', '$_GET', '$_REQUEST', '$_SERVER', '$GLOBALS' );
if ( false !== strpos( $line, ' $action ' ) )
$set_variables[] = '$action';
}
 
if ( preg_match( '/^\s+global (\$[a-zA-Z_\x7f-\xff][, \$a-zA-Z0-9_\x7f-\xff,]*);/', $line, $match ) )
$set_variables = array_merge( $set_variables, explode( ", ", $match[1] ) );
 
if ( preg_match( '/^\s+(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s+=/', $line, $match ) )
$set_variables[] = $match[1];
 
if ( preg_match_all( '/\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $line, $variables ) ) {
foreach ( $variables[0] as $variable ) {
if ( ! in_array( $variable, $set_variables ) ) {
$found = true;
echo "[ $num ] $variable\n $line\n\n";
}
}
}
}

This is probably easier to use the tokenizer for. That way, you can check if a variable is declared within a block properly.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.