phpnullmigrationdeprecatedphp-8.1

Migration to PHP 8.1 - how to fix Deprecated Passing null to parameter error - rename build in functions


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

To fix this issue without going thrugh huge amount of code I was trying to rename 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(PECL apd) no longer works, last update on this is from 20041.

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

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

In PHP 8.1 when null is passed to build in function, it is no longer silently converted to empty string.


  1. https://pecl.php.net/package/apd

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: