【问题标题】:Trying to access array offset on value of type null尝试访问 null 类型值的数组偏移量
【发布时间】:2021-07-23 22:13:41
【问题描述】:

从 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")

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

【问题讨论】:

  • 首先检查isset($this->config)isset($this->config['backend'])isset($this->config['backend']['api_prefix'])
  • 好吧,我想知道为什么,但它没有在这个文件中加载配置——即使代码根本没有改变。因此,如果您从中创建答案,我可以接受它作为一个好的答案,因为我可以通过首先在此处调用加载配置函数来解决此问题,谢谢!

标签: php php-7.4


【解决方案1】:

它与 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这通常是一个创可贴。如果应该设置变量,您不想抑制错误。
    【解决方案3】:

    听起来你的变量没有设置。

    检查以下 isset 调用:

    isset($this->config); 
    isset($this->config['backend']);
    isset($this->config['backend']['api_prefix']);
    

    实际上,您可以在一次 isset 调用 (isset($x, $y, $z)) 中检查多个变量,但这会让您查看具体缺少哪个变量

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 2021-01-09
      • 2020-09-08
      • 2021-11-30
      相关资源
      最近更新 更多