psalm icon indicating copy to clipboard operation
psalm copied to clipboard

Global variable reported as unused when only used inside a function

Open Boris-de opened this issue 1 year ago • 1 comments

I'm running psalm on some very old code and noticed that there it does incorrectly detects a global variable defined on the top-level but only used inside functions as UnusedVariable.

https://psalm.dev/r/bf4352de92

~~Additionally @psalm-suppress UnusedVariable does not seem to have an effect on this.~~ (I could swear I successfully used this somewhere, but I just read that unused variables should be suppressed by an underscore in the variable name. Never mind this then)

I refactored the code on my side, but thought it might still be interesting to report this.

Boris-de avatar Feb 04 '24 09:02 Boris-de

I found these snippets:

https://psalm.dev/r/bf4352de92
<?php
function fun(string $path): string
{
  global $SERVER_NAME;
  return $SERVER_NAME ? "https://$SERVER_NAME/$path" : '';
}

if (!isset($SERVER_NAME)) {
  /** @psalm-suppress UnusedVariable */
  $SERVER_NAME = 'foo';
}

echo fun('bar');
Psalm output (using commit bf57d59):

INFO: UnusedVariable - 10:3 - $SERVER_NAME is never referenced or the value is not used

psalm-github-bot[bot] avatar Feb 04 '24 09:02 psalm-github-bot[bot]