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

[DangerousDowngrade PHP 7.3] List reference assignment inside foreach #4376

Closed
leoloso opened this issue Oct 9, 2020 · 1 comment
Closed
Labels

Comments

@leoloso
Copy link
Contributor

leoloso commented Oct 9, 2020

Feature Request

This is the continuation from #4315 and #4371, to downgrade the list reference assignment inside a foreach:

$array = [[1, 2], [3, 4]];
foreach ($array as list(&$a, $b)) {
    $a = 7;
}
var_dump($array);
/*
array(2) {
  [0]=>
  array(2) {
    [0]=>
    int(7)
    [1]=>
    int(2)
  }
  [1]=>
  array(2) {
    [0]=>
    &int(7)
    [1]=>
    int(4)
  }
}
*/

According to the RFC this is not downgradable:

The predominant advantage of adding support for this is that it allows you to use reference assignment for multiple variables at once, which is not currently possible. [...] the advantage here is that you can reference assign some, but not all of the variables in list().

After running this PHP code, the reference exists on $array[1][0] since $a is still in scope after the foreach(). This part cannot be reproduced in PHP 7.2

If we didn't care about the references, but only about the final values, this is doable:

$array = [[1, 2], [3, 4]];
foreach ($array as &$item) {
    $item[0] = 7;
}
var_dump($array);
/*
array(2) {
  [0]=>
  array(2) {
    [0]=>
    int(7)
    [1]=>
    int(2)
  }
  [1]=>
  &array(2) {
    [0]=>
    int(7)
    [1]=>
    int(4)
  }
}
*/

Notice how the reference at the end points to the 2nd item in the array, and not to the 1st element of that item.

Hence, the final references cannot be recreated, but the values can.

Suggestion

Create a new set DANGEROUS_DOWNGRADE_PHP73, and call this rule DangerousDowngradeListReferenceAssignmentInsideForeachRector

Diff

$array = [[1, 2], [3, 4]];
-foreach ($array as list(&$a, $b)) {
-    $a = 7;
+foreach ($array as &$item) {
+    $item[0] = 7;
}
@TomasVotruba
Copy link
Member

TomasVotruba commented Dec 9, 2020

References are very rare to be seen in modern code. We should focus on other issues, untill this one appears in real downgraded code. Closing for now

TomasVotruba added a commit that referenced this issue Jun 29, 2023
rectorphp/rector-src@29dc584 Add float mul integer type to NumericReturnTypeFromStrictScalarReturnsRector (#4376)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants