php / php/php-src

Assigning property value through readonly array results in "Cannot modify readonly property"

Offen
#15,912 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Bug Category: Engine Status: Needs Triage
Vorherrschende Sprache
C
Sterne
40.4k
Forks
8.2k
Ø Merge
2 T. 13 Std.
Gemergte PRs (30 T.)
96

Beschreibung

Description

The following code:

<?php
class A {
    public function __construct(
        public readonly array $a,
    ) {}
}

class B {
    public function __construct(
        public string $b,
    ) {
    }
}

$a = new A([ new B('foo') ]);
$a->a[0]->b = 'bar';

echo $a->a[0]->b;

Resulted in this output:

PHP Fatal error:  Uncaught Error: Cannot modify readonly property A::$a in /test.php:17

But I expected this output instead:

bar

If you try to change the property of an object that is inside a readonly array, based on syntax it thinks you're change the array itself and throws a Fatal, even though that property we're actually trying to change ($a->a[0]->b) is not readonly and can be changed. If the code to change the B::$b property is refactored like this the code works as expected:

$a = new A([ new B('foo') ]);
$b = $a->a[0];
$b->b = 'bar';
PHP Version

8.2.23, 8.3.11

Operating System

No response

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginnen Sie damit, den bereitgestellten Reproducer unter PHP 8.2.23 und 8.3.11 auszuführen und ihn mit dem refaktorierten Zugriff über eine temporäre Variable zu vergleichen. Verfolgen Sie die Behandlung von readonly-Properties für den direkten Ausdruck $a->[0]->b im PHP-Interpreter; als erledigt gilt dies, wenn die direkte Zuweisung B::$b aktualisiert und bar ohne fatalen Fehler ausgibt.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
php
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Klar beschrieben
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.