phpstan-rules icon indicating copy to clipboard operation
phpstan-rules copied to clipboard

[suggestion] No shadow variable

Open Minishlink opened this issue 6 months ago • 1 comments

Hello,

I'm working on a PHP project right now and found this bug:

public function get(string $id): ?Model
    {
        if ($this->models === null) {
            $this->models = [];
            $modelsData = $this->resolver->getList($this->operator->getId(), ids: array_keys($this->buffer));

            foreach (array_keys($this->buffer) as $bufferedId) {
                $this->models[$bufferedId] = null;
            }

            //  function argument $id is overridden here 
            foreach ($modelsData as $id => $modelDatum) {
                $this->models[$id] = $modelDatum;
            }
        }
        
        // so now the $id is not function's $id the the last $id of the above foreach
        return $this->models[$id] ?? null;
    }

I feel like it would make sense to have a rule that prevents this, but it's been a while I haven't done any serious PHP so I'm not sure how is the state of static analysis in PHP

Minishlink avatar Aug 31 '25 08:08 Minishlink

Some time ago I implemented generic variable overwriting rule, but was not satisfied with the results (too many ignores of valid cases). But maybe some specific cases like the suggested one (foreach introduced variables) might make sense.

janedbal avatar Sep 01 '25 08:09 janedbal

Variable overwrite in a loop is now checked by phpstan/phpstan-strict-rules

$i = 1;
$foo = [1,2,3];
foreach ($foo as $i) {
	echo $i;
}

mabar avatar Dec 03 '25 03:12 mabar

Right, so closing. Thx

janedbal avatar Dec 03 '25 07:12 janedbal