Skip to content

Do not close scope of ref reassignment when inside else - #306

Merged
sirbrillig merged 5 commits into
2.xfrom
fix/pass-by-reference-unused
Aug 5, 2023
Merged

Do not close scope of ref reassignment when inside else#306
sirbrillig merged 5 commits into
2.xfrom
fix/pass-by-reference-unused

Conversation

@sirbrillig

@sirbrillig sirbrillig commented Aug 5, 2023

Copy link
Copy Markdown
Owner

When we reassign a reference variable, we need to know if it has been used first. This is because changing the reference of a variable is like creating a new variable; if its previous value was never used, then we should report an unused variable.

For example, this is the intended behavior:

$foo = &$bar;  // Warning that $foo is unused because once it is reassigned, it is a different variable.
$foo = &$yaz;
echo $foo;

However, because conditional statements might or might not be run, we must assume that assignments by reference might not happen and should not trigger a warning even if it appears they are unused.

This example reassignment should not trigger a warning:

$foo = &$bar; // No warning because we cannot be sure that the next assignment will happen.
if ( $x ) {
  $foo = &$yaz;
}
echo $foo;

This logic already exists, but before this PR it does not apply to else blocks or elseif blocks, only if.

For example, this code should not trigger a warning, but it does before this PR:

if ( $x ) {
  $foo = &$bar; // No warning because we cannot be sure that the 'else' assignment will happen.
} else {
  $foo = &$yaz;
}
echo $foo;

In this PR we extend that logic to also cover else and elseif.

Fixes #305

@sirbrillig
sirbrillig merged commit 3b71162 into 2.x Aug 5, 2023
@sirbrillig
sirbrillig deleted the fix/pass-by-reference-unused branch August 5, 2023 23:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Variable reported as unused on an assignment by reference

1 participant