首页 > 解决方案 > 不推荐使用带有花括号的数组和字符串偏移访问语法

问题描述

我刚刚将我的 php 版本更新到 7.4,我注意到弹出了这个错误:

不推荐使用带有花括号的数组和字符串偏移访问语法

这是触发上述错误的我的代码的一部分:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result{0}->id)) {
        return $records->result{0}->id;
    }
    return false;
}

我的项目中很少有库使用花括号来获取字符串中的单个字符,更改语法问题的最佳方法是什么?

标签: phpphp-7.4

解决方案


解决这个问题真的很简单,但是请记住,您应该为您在其存储库中使用的每个库分叉并提交您的更改,以帮助其他人。

假设您的代码中有这样的内容:

$str = "test";
echo($str{0});

由于 PHP 7.4 花括号方法在字符串中获取单个字符已被弃用,因此将上述语法更改为:

$str = "test";
echo($str[0]);

修复问题中的代码将如下所示:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

推荐阅读