phpnullmigrationdeprecatedphp-8.1

Migration to PHP 8.1 - how to fix Deprecated Passing null to parameter error


PHP 8.1 has deprecated passing null as a parameter to a lot of core functions. My main problem is with functions like htmlspecialchars and trim, where null is no longer silently converted to the empty string.

To fix this issue without going through a huge amount of code I was trying to rename the original built-in functions and replace them with wrappers that cast input from null to (empty) string.

My main problem with this approach is, that the function rename_function (from PECL apd) no longer works; last update on this is from 2004 1.

I need some sort of override of built-in functions, to avoid writing null checks each time a function is called making all my code two times larger.

The only other solution I can think of is to use only my custom functions, but this still require going through all my code and third party libraries I have.



Solution

  • Firstly, two things to bear in mind:

    1. PHP 8.1 deprecates these calls, it does not make them errors. The purpose of deprecation is to give authors advance notice to fix their code, so you and the authors of libraries you use have until PHP 9.0 comes out to fix things. So, don't panic that not everything is fixed right away, and be patient with library maintainers, who will get to this in their own time.
    2. The quick fix in most cases is to use the null coalescing operator to provide a default value as appropriate, so you don't need a long null check around every use. For instance, htmlspecialchars($something) can be replaced with htmlspecialchars($something ?? '')

    Next, some options: