Skip to content

Commit 6d6fade

Browse files
BogdanUngureanunikic
authored andcommitted
Improved error message for typed class properties with null as default value
Closes GH-6396.
1 parent 94938e4 commit 6d6fade

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
--TEST--
2+
Nullable default property error message
3+
--FILE--
4+
<?php
5+
6+
class A {
7+
public string|int $b = null;
8+
}
9+
10+
$t = new A;
11+
$t->b;
12+
13+
?>
14+
--EXPECTF--
15+
Fatal error: Default value for property of type string|int may not be null. Use the nullable type string|int|null to allow null default value in %s on line %d

Zend/zend_compile.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7042,10 +7042,13 @@ void zend_compile_prop_decl(zend_ast *ast, zend_ast *type_ast, uint32_t flags, z
70427042
&& !zend_is_valid_default_value(type, &value_zv)) {
70437043
zend_string *str = zend_type_to_string(type);
70447044
if (Z_TYPE(value_zv) == IS_NULL) {
7045+
ZEND_TYPE_FULL_MASK(type) |= MAY_BE_NULL;
7046+
zend_string *nullable_str = zend_type_to_string(type);
7047+
70457048
zend_error_noreturn(E_COMPILE_ERROR,
70467049
"Default value for property of type %s may not be null. "
7047-
"Use the nullable type ?%s to allow null default value",
7048-
ZSTR_VAL(str), ZSTR_VAL(str));
7050+
"Use the nullable type %s to allow null default value",
7051+
ZSTR_VAL(str), ZSTR_VAL(nullable_str));
70497052
} else {
70507053
zend_error_noreturn(E_COMPILE_ERROR,
70517054
"Cannot use %s as default value for property %s::$%s of type %s",

0 commit comments

Comments
 (0)