Repository navigation
Conversation
foreach can assign by reference to a property, an array element or a
static property, not just to a variable. The parser marks such a value
with byref, but only the variable printer prints the &, so
foreach ($test as $key => &$array[$key]) {}
was formatted as `foreach ($test as $key => $array[$key]) {}`, which
assigns by value and silently changes what the loop does.
The foreach printer now adds the & itself for a byref value that is not
a variable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Bug:
foreachcan assign by reference to a property, an array element or a static property, not only to a variable:The parser marks the value with
byref, but only thevariableprinter prints the&, so these were formatted asforeach ($test as $object->property)andforeach ($test as $key => $array[$key]). The loop then assigns by value instead of binding a reference, which silently changes what it does.Fix: in the
foreachprinter (src/printer.mjs), abyrefvalue that is not a plainvariablegets the&printed in front of it. Variables still print their own&, soforeach ($a as &$v)is unchanged.Tests: added both forms above to
tests/foreach/foreach.phpand updated the snapshot. Without the fix, the snapshot test fails because the&is gone. With it,yarn test:nodepasses (599 tests),AST_COMPARE=1 yarn test:nodepasses andyarn lintis clean.I found this by formatting the
--FILE--sections of php-src'sZend/testsand comparing nikic/PHP-Parser ASTs of the input and output.Zend/tests/foreach/foreach_by_ref_to_property.phptandZend/tests/enum/no-write-properties-through-foreach-reference.phptchanged meaning before this change and round-trip after it.