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

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

Merged
merged 5 commits into from
Aug 5, 2023

Conversation

sirbrillig
Copy link
Owner

@sirbrillig sirbrillig commented Aug 5, 2023

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