Description
Hello!
I stumbled upon a weird "unused variable" warning that I feel is a false positive, so I thought I'd report this here.
First things first, the env I'm working on is phpcs v3.6.0 (stable), with phpcs-variable-analysis v 2.11.0.
The case is the following: I'm declaring a variable, that I conditionnallly assign to different array elements. The assignment is done by reference, because I actually need to manipulate those elements further down. Anyway. Long story short, if I do this I get an "Unused variable" warning message, even though the variable is used.
Here are some examples that all trigger the same message.
- The first one is close to the actual code I'm writing.
- The second one uses an else statement, just to make sure the variable will ever get assigned only once.
- For the third I tried to simplify as much as possible to get rid of potential external side effects.
function somefunc($arr) {
$var = [];
if (isset($arr['foo'])) {
$var = &$arr['foo'];
}
elseif (isset($arr['bar'])) {
$var = &$arr['bar'];
}
foreach ($var as $key => $value) {
$var[$key . '_plus_one'] = $value + 1;
}
return $arr;
}
function somefunc($arr) {
if (isset($arr['foo'])) {
$var = &$arr['foo'];
}
elseif (isset($arr['bar'])) {
$var = &$arr['bar'];
}
else {
$var = [];
}
foreach ($var as $key => $value) {
$var[$key . '_plus_one'] = $value + 1;
}
return $arr;
}
private function somefunc($choice, &$arr1, &$arr_default) {
$var = &$arr_default;
if ($choice) {
$var = &$arr1;
}
foreach ($var as $key => $value) {
$var[$key . '_plus_one'] = $value + 1;
}
}
And here are two pieces of code that do not trigger the message. They are both based on the last one above.
- The first one has the conditional assignment removed entirely.
- The second one has the conditional assignment done by value and not by reference.
(Obviously, both of these don't produce the expected result when run, so they're not valid workarounds.)
private function somefunc($choice, &$arr1, &$arr_default) {
$var = &$arr_default;
foreach ($var as $key => $value) {
$var[$key . '_plus_one'] = $value + 1;
}
}
private function somefunc($choice, &$arr1, &$arr_default) {
$var = &$arr_default;
if ($choice) {
$var = $arr1;
}
foreach ($var as $key => $value) {
$var[$key . '_plus_one'] = $value + 1;
}
}
So it looks to me like this is the conditional re-assignment that makes the message pop up. I don't know the standards very well so it's possible that this pattern goes against some rule I don't know of, but "unused variable" sounds pretty misleading to me.