Skip to content

Commit 0897266

Browse files
committed
Fix GH-9285 Traits cannot be used in readonly classes
1 parent d7383ed commit 0897266

File tree

4 files changed

+52
-1
lines changed

4 files changed

+52
-1
lines changed

NEWS

+2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ PHP NEWS
77
(Tim Starling)
88
. Fixed bug GH-9227 (Trailing dots and spaces in filenames are ignored).
99
(cmb)
10+
. Fixed bug GH-9285 (Traits cannot be used in readonly classes).
11+
(kocsismate)
1012

1113
- Streams:
1214
. Fixed bug GH-9316 ($http_response_header is wrong for long status line).
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
--TEST--
2+
Bug GH-9285: PHP 8.2 readonly classes allow inheriting mutable properties from traits - error
3+
--FILE--
4+
<?php
5+
6+
trait T {
7+
public $prop;
8+
}
9+
10+
readonly class C {
11+
use T;
12+
}
13+
14+
?>
15+
--EXPECTF--
16+
Fatal error: Readonly class C cannot use trait with a non-readonly property T::$prop in %s on line %d
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
--TEST--
2+
Bug GH-9285: PHP 8.2 readonly classes allow inheriting mutable properties from traits - success
3+
--FILE--
4+
<?php
5+
6+
trait T {
7+
public readonly int $prop;
8+
}
9+
10+
readonly class C {
11+
use T;
12+
13+
public function __construct()
14+
{
15+
$this->prop = 1;
16+
}
17+
}
18+
19+
$c = new C();
20+
var_dump($c->prop);
21+
22+
?>
23+
--EXPECT--
24+
int(1)

Zend/zend_inheritance.c

+10-1
Original file line numberDiff line numberDiff line change
@@ -2368,7 +2368,7 @@ static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_ent
23682368

23692369
if (!is_compatible) {
23702370
zend_error_noreturn(E_COMPILE_ERROR,
2371-
"%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed",
2371+
"%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed",
23722372
ZSTR_VAL(find_first_property_definition(ce, traits, i, prop_name, colliding_prop->ce)->name),
23732373
ZSTR_VAL(property_info->ce->name),
23742374
ZSTR_VAL(prop_name),
@@ -2378,6 +2378,15 @@ static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_ent
23782378
}
23792379
}
23802380

2381+
if ((ce->ce_flags & ZEND_ACC_READONLY_CLASS) && !(property_info->flags & ZEND_ACC_READONLY)) {
2382+
zend_error_noreturn(E_COMPILE_ERROR,
2383+
"Readonly class %s cannot use trait with a non-readonly property %s::$%s",
2384+
ZSTR_VAL(ce->name),
2385+
ZSTR_VAL(property_info->ce->name),
2386+
ZSTR_VAL(prop_name)
2387+
);
2388+
}
2389+
23812390
/* property not found, so lets add it */
23822391
if (flags & ZEND_ACC_STATIC) {
23832392
prop_value = &traits[i]->default_static_members_table[property_info->offset];

0 commit comments

Comments
 (0)