John Davidson

Passing null to non-nullable internal function parameters - Updating Existing Code Base to php 8.1

0 comments
Message:


I am just getting started on upgrading my code to be php 8.1 compatible. I have many pieces of code where I am passing potentially null values to internal functions.


if (strlen($row) > 0) {
...
}

Where $row comes from a source that may have null values (e.g. a query). This can generate a deprecation warning; in this case:



Deprecated: strlen(): Passing null to parameter #1 ($string) of type string is deprecated



I'm looking for the easiest most time efficient way to handle upgrading this code, for example fixes where global search and replaces are possible. It seems that type casting the variable I pass to an internal function works without changing functionality.


error_reporting(E_ALL);
$row = null;

if (strlen((string) $row) > 0) {
...
}

Aside from the moral aspects of coding this way, are there issues with this approach for internal functions? Are there better ways (other than completely rewriting the code and handling nulls differently)? I prefer this solution backwards compatible to v7.4, although I could possibly live with 8.0 compatibility.


I am aware my user defined functions have other choices.



My Answer:
> 0) {
// do something with $row
}

_This code will throw a warning in PHP 8.1 because `strlen()` expects a string and not null. To update this code to be PHP 8.1 compatible, you can check if `$row` is not null before passing it to `strlen()`._

php
if ($row !== null && strlen($row) > 0) {
// do something with $row
}


_By adding the check for `$row !== null`, you ensure that only non-null values are passed to `strlen()`, avoiding any potential warnings in PHP 8.1._

_You can apply this same pattern to other internal functions that expect non-nullable parameters. By checking for null values before passing them to these functions, you can ensure that your code remains compatible with PHP 8.1._

Rate this post

3 of 5 based on 5998 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us