Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False positive unused variable when that variable is a reference #927

Open
arichard4 opened this issue Dec 12, 2021 · 2 comments
Open

False positive unused variable when that variable is a reference #927

arichard4 opened this issue Dec 12, 2021 · 2 comments
Labels

Comments

@arichard4
Copy link

  • PHPMD version: 2.10.2snapshot202107221018
  • PHP Version: 8.0.13
  • Installation type: phar file
  • Operating System / Distribution & Version: Arch Linux

Current Behavior

PHPMD doesn't seem to have special handling for variables that are references (though it does seem to handle reference parameters correctly).

<?php

function func() {
	$a = 1;
	$b = &$a;
	$b = 2;
	print($a);
}

func();
$ ./phpmd.phar test.php text unusedcode
test.php:5	Avoid unused local variables such as '$b'.

However, $b is used.

#720 seems relevant but distinct.

Here's a less simplified example demonstrating why someone might use this:

<?php

class A {
	private static $cache = [];
	private static function &GetCache() {
		// Imagine that instead of returning the same cache, this instead
		// was shared logic to decide one of a number of caches to return
		return static::$cache;
	}

	public static function ClearCache() {
		$cache = &static::GetCache();

		$cache = [];
	}

	public static function InsertToCache($key, $value) {
		$cache = &static::GetCache();
		$cache[$key] = $value;
	}
}

PHPMD warns about ClearCache. (Curiously, it doesn't warn about InsertToCache- testing elsewhere, it seems like an array insertion is considered using a variable?)

@tvbeek tvbeek added the Bug label Apr 12, 2022
@tvbeek
Copy link
Member

tvbeek commented Apr 12, 2022

@arichard4 Thanks for the report. Are you able to provide a PR (with a solution or only with a failing test?) That can help in solving this 😃

arichard4 added a commit to arichard4/phpmd that referenced this issue Apr 17, 2022
@arichard4
Copy link
Author

I submitted a PR with a failing test.

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

No branches or pull requests

2 participants