WordPress后台警告建议更新 PHP 版本
您的站点正在运行过时版本的 PHP (8.0.26),其无法接收安全更新,且应当被升级。
什么是 PHP?为什么它影响我的站点?
PHP 是用于搭建 WordPress 的编程语言之一。较新版本的 PHP 能接受定期安全更新,也能提升您网站的性能。 PHP 的最低建议版本为 8.3。
于是决定逐步将所有PHP网站全部迁移到PHP8.0环境。记录一下过程,可作参考。
一、常见错误
1.1 Passing null
Deprecated: strlen(): Passing null to parameter #1 ($string) of type string is deprecated
这个错误是因为在 PHP 8.1+ 中,将 null 传递给 strlen() 函数会触发弃用警告。提供几种解决方案:
1. 使用空值合并运算符(推荐)
// 原来的问题代码
$length = strlen($variable);
// 修复后的代码
$length = strlen($variable ?? '');
2. 使用三元运算符
$length = strlen($variable !== null ? $variable : '');
3. 添加条件检查
if ($variable !== null) {
$length = strlen($variable);
} else {
$length = 0; // 或者其他默认值
}
4. 类型安全的方法
$length = is_string($variable) ? strlen($variable) : 0;
1.2 Use of “self” in callables is deprecated
Deprecated: Use of “self” in callables is deprecated in
例子1:
public static function _($messageId)
{
return forward_static_call_array('self::translate', func_get_args());
}
上面代码存在的问题
-
使用了
forward_static_call_array函数(在 PHP 8.4 中不推荐使用) -
在可调用对象中使用字符串
'self'(在 PHP 8.4 中已弃用)
解决方案1:使用可变参数和静态调用(推荐)
public static function _($messageId)
{
return static::translate(...func_get_args());
}
解决方案2:使用 call_user_func_array 配合 static::class
public static function _($messageId)
{
return call_user_func_array([static::class, 'translate'], func_get_args());
}
例子2:
$secondLevel = array_filter(
scandir($mainpath . DIRECTORY_SEPARATOR . $firstLevel[$firstKey]),
'self::_isSecondLevelDir'
);
上面代码中的问题是在 array_filter 中使用字符串 'self::_isSecondLevelDir' 作为回调函数。在 PHP 8.4 中,这种使用 self 的可调用字符串形式已被弃用。
解决方案1:使用数组形式的回调(推荐)
$secondLevel = array_filter(
scandir($mainpath . DIRECTORY_SEPARATOR . $firstLevel[$firstKey]),
[static::class, '_isSecondLevelDir']
);
解决方案2:使用闭包函数
$secondLevel = array_filter(
scandir($mainpath . DIRECTORY_SEPARATOR . $firstLevel[$firstKey]),
function($item) {
return static::_isSecondLevelDir($item);
}
);
1.3 null 的参数类型声明
Implicitly marking parameter $expire as nullable is deprecated, the explicit nullable type must be used instead
public static function putCache(string $key, $value, int $expire = null)
出现错误是因为在 PHP 8.4 中,对可为 null 的参数类型声明要求更加严格。你需要将 int $expire = null 改为显式的可空类型 ?int $expire = null。
public static function putCache(string $key, $value, ?int $expire = null)
未完待续