Skip to content

Instantly share code, notes, and snippets.

@nacin
Created January 20, 2012 22:34
Show Gist options
  • Save nacin/1650009 to your computer and use it in GitHub Desktop.
Save nacin/1650009 to your computer and use it in GitHub Desktop.
Find Unset Local Variables
<?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";
}
}
}
}
@rmccue
Copy link

rmccue commented Jan 22, 2012

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment