尝试访问 null 类型值的数组偏移量

从 php 7.1 迁移到 7.4。我们对一个 API 进行了大约 500 个功能测试,其中一些在迁移完成后开始失败并出现错误。这些测试以前到处都是通过,现在到处都失败了——不是全部,只有 39 个。


环境信息:


php 7.4

密码接收

yii2

堆栈跟踪:


...\api\vendor\codeception\codeception\src\Codeception\Subscriber\ErrorHandler.php:83

...\api\tests\functional\SomeFileHereCest.php:72

...\api\vendor\codeception\codeception\src\Codeception\Lib\Di.php:127

...\api\vendor\codeception\codeception\src\Codeception\Test\Cest.php:138

...\api\vendor\codeception\codeception\src\Codeception\Test\Cest.php:97

...\api\vendor\codeception\codeception\src\Codeception\Test\Cest.php:80

...\api\vendor\codeception\codeception\src\Codeception\Test\Test.php:88

... more stuff here, not important

由于ErrorHandler.php:83这只是捕获错误,让我们看一下SomeFileHereCest.php:72:


// declaration of the apiPrefix variable in the class.

protected $apiPrefix;

//...


public function _before(FunctionalTester $I)

{

    $this->apiPrefix = $this->config['backend']['api_prefix']; // this is the line 72

    //... more similar stuff later

所以$this->config['backend']['api_prefix']这是一个字符串(“v1”)


而且我看不出问题出在哪里以及如何更深入地研究它。有任何想法吗?


慕雪6442864
浏览 269回答 3
3回答

慕斯709654

听起来你的变量没有设置。检查以下 isset 调用:isset($this->config); isset($this->config['backend']);isset($this->config['backend']['api_prefix']);您实际上可以在一次 isset 调用 ( isset($x, $y, $z)) 中检查多个 var,但这会让您查看具体缺少哪个 var

森林海

使用 (??) ( double question mark operator) (" null coalescing operator") 来避免未设置的数组。这个单元测试给了我“成功”class PhpTest extends TestCase{    public function test_php_74()    {        //Trying to access array offset on value of type null        $this->assertSame('7.4.9', phpversion());        $a = null;        $this->assertTrue($a ?? true);        $this->assertTrue($a['a'] ?? true);        $this->assertTrue($a['a']['a'] ?? true);        $a = [];        $this->assertSame([], $a);        $this->assertTrue($a['a'] ?? true);        $this->assertTrue($a['a']['a'] ?? true);    }}

梵蒂冈之花

它与 PHP 7.4 问题有关。解决方案是我们可以将 isset 放在 PHP 或 Laravel Blade 旧代码中@foreach ($widgets->get('dashboard') as $widget) {!! $widget->render() !!}@endforeach使用 isset 更新新代码@if(isset($Widget))@foreach ($widgets->get('dashboard') as $widget)    {!! $widget->render() !!}@endforeach@endif
打开App,查看更多内容
随时随地看视频慕课网APP