php / php/php-src

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

オープン
#15,912 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

Bug Category: Engine Status: Needs Triage
主要言語
C
スター
40.4k
フォーク
8.2k
平均マージ
2日 13時間
マージ済み PR(30日)
96

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、提供された再現コードを PHP 8.2.23 と 8.3.11 で実行し、一時変数を介したリファクタリング後のアクセスと比較します。PHP インタープリターで、直接の $a->[0]->b 式に対する readonly プロパティの処理を追跡します。直接代入によって B::$b が更新され、致命的なエラーなしで bar が出力されれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
php
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。