Magento扩展PHP 8.1.7版本strpos()废弃警告问题求助
Magento扩展PHP8.1.7废弃警告修复
问题信息
- 环境:PHP 8.1.7、Magento
- 错误提示:
废弃功能警告:strpos(): 将null传递给类型为string的参数#1 ($haystack)已被废弃,位于Setup/ChangeMethodsFormat.php第40行 - 涉事代码片段:
$oldMethods = $rule->getMethods(); if (strpos($oldMethods, "\n") === false) { continue; }
问题原因
PHP 8.1起,将null传入strpos这类要求接收字符串类型参数的函数会触发废弃警告。这里$rule->getMethods()可能返回null(比如对应规则未设置方法字段),直接传给strpos就触发了警告。
修复方案
两种可靠修复方式,任选其一即可:
方式1:强制类型转换
将$oldMethods强制转为字符串,自动把null转为空字符串,保证strpos接收的参数类型合法:
$oldMethods = $rule->getMethods(); $oldMethods = (string)$oldMethods; // null会被转为空字符串 if (strpos($oldMethods, "\n") === false) { continue; }
方式2:先做类型校验
先判断$oldMethods是否为有效字符串,再执行后续逻辑,更严谨:
$oldMethods = $rule->getMethods(); // 非字符串类型或找不到换行符时直接跳过 if (!is_string($oldMethods) || strpos($oldMethods, "\n") === false) { continue; }
两种方式都能消除警告,且不改变原代码的业务逻辑。
内容的提问来源于stack exchange,提问作者Oscar
相关产品推荐
相关产品推荐

