|
| 1 | +--TEST-- |
| 2 | +Promoted readonly property reassignment in constructor - child class cannot reassign parent's property |
| 3 | +--FILE-- |
| 4 | +<?php |
| 5 | + |
| 6 | +class Parent_ { |
| 7 | + public function __construct( |
| 8 | + public readonly string $prop = 'parent default', |
| 9 | + ) { |
| 10 | + // Parent can reassign its own promoted property |
| 11 | + $this->prop = 'parent set'; |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +class Child extends Parent_ { |
| 16 | + public function __construct() { |
| 17 | + parent::__construct(); |
| 18 | + // Child cannot reassign parent's promoted property |
| 19 | + try { |
| 20 | + $this->prop = 'child override'; |
| 21 | + } catch (Error $e) { |
| 22 | + echo $e->getMessage(), "\n"; |
| 23 | + } |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +$parent = new Parent_(); |
| 28 | +var_dump($parent->prop); |
| 29 | + |
| 30 | +$child = new Child(); |
| 31 | +var_dump($child->prop); |
| 32 | + |
| 33 | +// Even when child has its own promoted property |
| 34 | +class Parent2 { |
| 35 | + public function __construct( |
| 36 | + public readonly string $parentProp = 'parent default', |
| 37 | + ) { |
| 38 | + $this->parentProp = 'parent set'; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +class Child2 extends Parent2 { |
| 43 | + public function __construct( |
| 44 | + public readonly string $childProp = 'child default', |
| 45 | + ) { |
| 46 | + parent::__construct(); |
| 47 | + // Child can reassign its own promoted property |
| 48 | + $this->childProp = 'child set'; |
| 49 | + // But cannot reassign parent's promoted property |
| 50 | + try { |
| 51 | + $this->parentProp = 'child override'; |
| 52 | + } catch (Error $e) { |
| 53 | + echo $e->getMessage(), "\n"; |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +$child2 = new Child2(); |
| 59 | +var_dump($child2->parentProp, $child2->childProp); |
| 60 | + |
| 61 | +?> |
| 62 | +--EXPECT-- |
| 63 | +string(10) "parent set" |
| 64 | +Cannot modify readonly property Parent_::$prop |
| 65 | +string(10) "parent set" |
| 66 | +Cannot modify readonly property Parent2::$parentProp |
| 67 | +string(10) "parent set" |
| 68 | +string(9) "child set" |
0 commit comments