php / php/php-src

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

Aperta
#15,912 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Bug Category: Engine Status: Needs Triage
Lingua principale
C
Stelle
40.4k
Fork
8.2k
Merge medio
2g 13h
PR unite (30g)
96

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo il reproducer fornito su PHP 8.2.23 e 8.3.11 e confrontalo con l’accesso rifattorizzato tramite una variabile temporanea. Traccia la gestione delle proprietà readonly per l’espressione diretta $a->[0]->b nell’interprete PHP; il lavoro è completato quando l’assegnazione diretta aggiorna B::$b e stampa bar senza un errore fatale.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
php
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.