Cannot use %s as default value for property %s::$%s of type %s

Description

The default value of the property is not compatible with the type of the same property. In the example here, the property $s is an integer, but has a string as default value.

This error also applies to numeric strings: the default value must be of the same type, without any silent type juggling.

It used to be recommended to make the default value NULL as it would be implicitely accepted by the type. Yet, in PHP 8.4, this is now a deprecated behavior, and it is not recommended anymore.

Example

<?php

class X {
    public string $property = 3;
}

?>

Literal Examples

  • Cannot use 3 as default value for property X::$property of type string

Solutions

  • Change the type of the parameter.

  • Change the default value.

  • Remove the default value.

  • Remove the type value.

  • Add a second union type to the paramter.