今天把 PHP 从7.3升级到7.4版本,然后 Lumen 框架报错了:Trying to access array offset on value of type null

{
	"message": "Trying to access array offset on value of type null",
	"exception": "ErrorException",
	"file": "/var/www/html/xxx/vendor/illuminate/cookie/CookieServiceProvider.php",
	"line": 20,
	"trace": [{
		"file": "/var/www/html/xxx/vendor/illuminate/cookie/CookieServiceProvider.php",
		"line": 20,
		"function": "Laravel\\Lumen\\Concerns\\{closure}",
		"class": "Laravel\\Lumen\\Application",
		"type": "->"
	}, {
		"file": "/var/www/html/xxx/vendor/illuminate/container/Container.php",
		"line": 829,
		"function": "Illuminate\\Cookie\\{closure}",
		"class": "Illuminate\\Cookie\\CookieServiceProvider",
		"type": "->"
	}, {
        ...
    }
}

定位到报错的代码文件:

<?php

namespace Illuminate\Cookie;

use Illuminate\Support\ServiceProvider;

class CookieServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('cookie', function ($app) {
            $config = $app->make('config')->get('session');

            return (new CookieJar)->setDefaultPathAndDomain(
                $config['path'], $config['domain'], $config['secure'], $config['same_site'] ?? null
            );
        });
    }
}

报错原因是,第17行 $config 变量的值为 null,而第20行使用数组形式访问了 null 值,在 php7.4 里面会抛出 notice。

 

PHP 7.4 有一条不向后兼容的变更:https://www.php.net/manual/zh/migration74.incompatible.php

以数组形式访问非数组

尝试以数组方式访问 null,bool, int,float 或 resource (例如 $null["key"])将会抛出 notice 通知。

 

想起,之前在给 Lumen 框架添加 Cookie 支持的时候,参考了一篇文章:https://hdj.me/lumen-support-cookie/

文中有提到增加 session 配置,当时想着没用到 session,就没管了。现在才知道,这代码不能漏,还是乖乖补上吧。

也可以从 Laravel 官方 Git 仓库中获取这个 session.php 配置文件:https://raw.githubusercontent.com/laravel/laravel/8.x/config/session.php