Skip to content

modify readonly class property with reference #10844

Closed
@varrg

Description

@varrg

Description

The following code:

<?php
readonly class A implements IteratorAggregate {
	function __construct(readonly public string $foo = 'bar') {}
	
	function getIterator() : Traversable {
		return new ArrayIterator($this);
	}
}

$obj = new A;
//$obj->foo = 'baz';  // expected fatal error
//$prop = &$obj->foo;  // expected fatal error
foreach ($obj as $k => &$v) {
	$v = 'baz';
}

var_dump($obj);

Resulted in this output:

object(A)#1 (1) {
  ["foo"]=>
  &string(3) "baz"
}

But I expected this output instead:

Fatal error: Uncaught Error: Cannot modify readonly property A::$foo

PHP Version

8.2.3

Operating System

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions