phpcs-variable-analysis icon indicating copy to clipboard operation
phpcs-variable-analysis copied to clipboard

Variable variables are marked as unused

Open sirbrillig opened this issue 6 years ago • 0 comments

Originally described in #84.

Variables in PHP may have a dynamic symbol name, and are called variable variables. For example, the following function prints hello, which is a string stored in the variable $greeting, even though that variable is never explicitly mentioned:

function usedVariableVariable() {
  $greeting = 'hello';
  $varName = 'greeting';
  echo $$varName;
}

Here's the process I would imagine using to identify such a variable for the purposes of this sniff:

  1. Is the current variable defined? Good.
  2. Is the current variable preceded by a T_DOLLAR or a T_DOLLAR and a T_OPEN_CURLY_BRACKET? If so, it's a variable variable.
  3. Resolve the value of the current variable (this is extremely hard).
  4. Process the T_DOLLAR as though it were a variable with the symbol name of the resolved current variable.
  5. Start again at 1 since there may be several levels.

Step 3 is very difficult because it requires executing the PHP code or a deep static analysis. Maybe there's something else we can do, though?

sirbrillig avatar May 10 '19 21:05 sirbrillig