php 8.1 - explode():不推荐将 null 传递给字符串类型的参数 #2 ($string)

php 8.1 - explode(): Passing null to parameter #2 ($string) of type string is deprecated

我想解决 8.1 中一些已弃用的错误。

PHP Deprecated: explode(): Passing null to parameter #2 ($string) of type string is deprecated in...

//explode uids into an array
$comp_uids = explode(',', $result['comp_uids']);

$result['comp_uids'] 在这种情况下为空,这就是显示空错误的原因。我不确定他们为什么弃用这种能力,但是为了避免这种情况,推荐的更改是什么?我看到 strlen(): Passing null to parameter #1 ($string) of type string is deprecated 和其他一些使用 8.1.

的情况类似

如果值为 null.

,则使用 null 合并运算符将值默认为空字符串
$comp_uids = explode(',', $result['comp_uids'] ?? '');

不需要 explode null,你事先知道它不会 return 匹配。如果你真的想要 [''] 作为结果,那么明确地做它更直观:

$comp_uids = $result['comp_uids'] !== null ? explode(',', $result['comp_uids']) : [''];

对于您的程序员同行,我仍然觉得这有点 counter-intuitive。恕我直言,未找到 UID 概念最好用空数组表示,如果您也可以期望空字符串,则可以将它们与 null 一起处理:

$comp_uids = $result['comp_uids'] != '' ? explode(',', $result['comp_uids']) : [];

只需将参数转换为字符串,会将 null 转换为 ''。

$comp_uids = explode(',', (string)$result['comp_uids']);