Cannot use %s as default value for parameter $%s of type %s

Description

The default value of the parameter is not compatible with the type of the parameter. In the example here, the parameter $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

function foo(int $s = 's') { }

function bar(int $s = '1') { }

?>

Literal Examples

  • Cannot use 3 as default value for parameter $a of type array

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.