Skip to content

Commit

Permalink
Improved error message for typed class properties with null as defaul…
Browse files Browse the repository at this point in the history
…t value

Closes GH-6396.
  • Loading branch information
BogdanUngureanu authored and nikic committed Nov 3, 2020
1 parent 94938e4 commit 6d6fade
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
15 changes: 15 additions & 0 deletions Zend/tests/nullable_types/union_nullable_property_fails.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
--TEST--
Nullable default property error message
--FILE--
<?php

class A {
public string|int $b = null;
}

$t = new A;
$t->b;

?>
--EXPECTF--
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
7 changes: 5 additions & 2 deletions Zend/zend_compile.c
Original file line number Diff line number Diff line change
Expand Up @@ -7042,10 +7042,13 @@ void zend_compile_prop_decl(zend_ast *ast, zend_ast *type_ast, uint32_t flags, z
&& !zend_is_valid_default_value(type, &value_zv)) {
zend_string *str = zend_type_to_string(type);
if (Z_TYPE(value_zv) == IS_NULL) {
ZEND_TYPE_FULL_MASK(type) |= MAY_BE_NULL;
zend_string *nullable_str = zend_type_to_string(type);

zend_error_noreturn(E_COMPILE_ERROR,
"Default value for property of type %s may not be null. "
"Use the nullable type ?%s to allow null default value",
ZSTR_VAL(str), ZSTR_VAL(str));
"Use the nullable type %s to allow null default value",
ZSTR_VAL(str), ZSTR_VAL(nullable_str));
} else {
zend_error_noreturn(E_COMPILE_ERROR,
"Cannot use %s as default value for property %s::$%s of type %s",
Expand Down

0 comments on commit 6d6fade

Please sign in to comment.