143

I've just updated my php version to 7.4, and i noticed this error pops up:

Array and string offset access syntax with curly braces is deprecated

here is part of my code which is triggering the above error:

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;
}

there are few libraries in my project which is using curly braces to get individual characters inside a string, whats the best way to change the syntax issue?

Pezhvak
  • 7,358
  • 7
  • 26
  • 38
  • 3
    @AbraCadaver how is this duplicate of what you have suggested? – Pezhvak Dec 03 '19 at 18:26
  • What do you mean by "best way to fix this issue"? What exactly keeps you from simply fixing this issue by changing the code? – Nico Haase Dec 06 '20 at 11:42
  • 4
    @NicoHaase I guess he doesn't know what the right way to change it is? Which is probably why he's here asking on stackoverflow. – Dtipson Feb 04 '21 at 15:03
  • 1
    The specific answer in @Abra's canonical can be found here: https://stackoverflow.com/a/59158847/2943403 – mickmackusa Dec 15 '21 at 13:56

1 Answers1

286

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

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

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

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

Fixing the code in the question will look something like this:

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;
}
Pezhvak
  • 7,358
  • 7
  • 26
  • 38
  • 1
    Do you happen to know when the `$string{$pos}` syntax was introduced in PHP? It must be ancient. – Henk Poley Nov 10 '20 at 09:33
  • 19
    Ah, technically it was to be deprecated in PHP 5.1 (June 2008), but they forgot to add the code to notify people : https://wiki.php.net/rfc/deprecate_curly_braces_array_access#wasn_t_the_curly_brace_syntax_deprecated_once_before – Henk Poley Nov 10 '20 at 09:38
  • 1
    since which php version does this work? php5.1? – helle Jan 14 '21 at 15:21
  • 1
    @helle it was part of the language before it gets deprecated – Pezhvak Jan 16 '21 at 11:36
  • This is the correct fix, as explained in the 7.4 documentation: https://www.php.net/manual/en/migration74.deprecated.php#migration74.deprecated.core.array-string-access-curly-brace – thelr Mar 09 '21 at 13:36