Skip to content

[Php81] Skip readonly on property returned by reference in ReadOnlyPropertyRector#8108

Merged
TomasVotruba merged 1 commit into
mainfrom
tv-readonly-by-ref-return
Jun 29, 2026
Merged

[Php81] Skip readonly on property returned by reference in ReadOnlyPropertyRector#8108
TomasVotruba merged 1 commit into
mainfrom
tv-readonly-by-ref-return

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Problem

ReadOnlyPropertyRector made a promoted property readonly even when it is returned by reference from a & method(). Returning by reference lets callers hold and mutate the value, so the property cannot be readonly — PHP throws a fatal "Cannot acquire reference to readonly property" at runtime.

Spotted in the wild in infection: https://github.com/infection/infection/blob/HEAD/src/TestFramework/Tracing/Trace/TestLocations.php

final class TestLocations
{
    public function __construct(
        private array $byLine = [],
        private readonly array $byMethod = [],
    ) {
    }

    public function &getTestsLocationsBySourceLine(): array
    {
        return $this->byLine;
    }
}

The rule rewrote private array $byLine to private readonly array $byLine, which breaks the by-reference getter.

Fix

Add isPropertyReturnedByRef() guard. Before making a property/promoted param readonly, bail out if any method declared with & (returns by reference) returns $this-><property> (directly or as the base of a nested expression).

Added skip_returned_by_ref.php.inc fixture covering the case.

@TomasVotruba TomasVotruba merged commit eebd086 into main Jun 29, 2026
65 checks passed
@TomasVotruba TomasVotruba deleted the tv-readonly-by-ref-return branch June 29, 2026 09:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant