PHP 8.1: Passing null
to non-nullable internal function parameters is deprecated
In PHP, passing null
to a function/method parameter that is not declared nullable is not allowed. Prior to PHP 8.1, this restriction was only applied to user-land functions, and not internal functions.
From PHP 8.1, passing null
to a function/method parameter not declared nullable emits a deprecation notice. This is in preparation to remove this functionality to throw a \TypeError
exception in a future PHP version as it does already for user-land functions/methods.
For example, strlen
function expects the first parameter to be of type string
. By definition, it does not accept null
values (i.e. not declared as ?string
nor string|null
union type). For historical reasons, PHP allowed passing null
, for these parameters. This behavior is inconsistent from user-land functions/methods because they would have thrown a \TypeError
exception if null
is passed to a parameter type not declared as nullable.
strlen(null); // 0
Deprecated: strlen(): Passing null to parameter #1 ($string) of type string is deprecated in ... on line ...
This behavior was allowed in the first place for historical reasons. PHP 7.0's introduction of scalar types did not allow null
for parameters unless the parameter was explicitly declared nullable. However, internal functions were not changed to strictly enforce scalar types to ease upgrading to PHP 7.0.
In PHP 8.0, internal functions were updated to throw \TypeError
and \ValueError
exceptions instead of warnings.
This deprecation notice will likely occur often in legacy code bases that relied on PHP to coerce the default value for a parameter from
null
.
Upgrading null
parameters to default values
Code that uses null
in a function/method call in place of the default value will need to replace the null
value with the default value from the function declaration.
For example, a strlen(null)
call emits a deprecation, and the sensible upgrade to this call would be strlen('')
.
To bring another example, preg_split
function has a third parameter int $limit = -1
. Passing null
to this parameter emits a deprecation notice in PHP 8.1, and the sensible upgrade to this call would be setting $limit
parameter to -1
.
Backwards Compatibility Impact
This is a backwards-compatibility breaking change. Updating the null
parameters to adhere to the expected type should fix the deprecation notice across all PHP versions.
Further, it may be possible for automated code fixing tools to update said null
parameters to the default values from the function declaration.