PHP8.0升级PHP8.4常见代码编辑

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());        
}

上面代码存在的问题

  1. 使用了 forward_static_call_array 函数(在 PHP 8.4 中不推荐使用)

  2. 在可调用对象中使用字符串 '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)

未完待续

本文采用 CC BY-NC-SA 3.0 Unported 许可,转载请以超链接注明出处。
原文地址:PHP8.0升级PHP8.4常见代码编辑 作者:松鼠小
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
Source: Telegram @AmashiroNatsukiEars_NoWord Sticker
Source: Github @zhheo/Sticker-Heo
Source: github.com/k4yt3x/flowerhd
颜文字
AmashiroNatsukiEars
Heo
小恐龙
花!
上一篇