Pezhvak
Pezhvak

Reputation: 10868

Array and string offset access syntax with curly braces is deprecated

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?

Upvotes: 236

Views: 647832

Answers (2)

Gerard ONeill
Gerard ONeill

Reputation: 4102

"Array and string offset access"

I was confused because I was not doing string access. But the problem is much more general - to access any "array" (hash), you use the square brackets.

So:

$list = ("name1" => "value", "name2" => "value")

is accessed like:

$list["name2"]

which is not natural for languages (perl) where a has is accessed differently than a list. Although python treats it like an array also..

Upvotes: -1

Pezhvak
Pezhvak

Reputation: 10868

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

Upvotes: 452

Related Questions