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

Pez*_*vak 103 php php-7.4

我刚刚将我的 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Pez*_*vak 191

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

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

$str = "test";
echo($str{0});
Run Code Online (Sandbox Code Playgroud)

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

$str = "test";
echo($str[0]);
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 啊,从技术上讲,它在 PHP 5.1(2008 年 6 月)中已被弃用,但他们忘记添加代码来通知人们:https://wiki.php.net/rfc/deprecate_curly_braces_array_access#wasn_t_the_curly_brace_syntax_deprecated_once_before (11认同)
  • 这是正确的修复,如 7.4 文档中所述:https://www.php.net/manual/en/migration74.deprecated.php#migration74.deprecated.core.array-string-access-curly-brace (2认同)