Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to string conversion in Php7

Tags:

php

symfony

I am trying to execute this code (it was working on php5, now I'am on php7):

$this->links->$data[$te]['attributes']['ID'] = $data[$te]['attributes']['URL'];

But I get this error:

ContextErrorException: Notice: Array to string conversion

Thanks in advance

like image 594
CrazyDeveloper Avatar asked Oct 09 '17 15:10

CrazyDeveloper


1 Answers

This is down to the change in how complex variables are resolved in PHP 5 vs 7. See the section on Changes to variable handling here: http://php.net/manual/en/migration70.incompatible.php

The difference is that the expression:

$this->links->$data[$te]['attributes']['ID']

is evaluated like this in PHP 5:

$this->links->{$data[$te]['attributes']['ID']}

and like this in PHP 7:

($this->links->$data)[$te]['attributes']['ID']

See https://3v4l.org/gB0rQ for a cut-down example.

You'll need to amend your code to be explicit, either by using {} as appropriate, or by breaking it down into two lines. In this case, where you've got code that works fine in PHP 5, pick the former, since it will mean the behaviour stays consistent in all versions of PHP.

like image 80
iainn Avatar answered Oct 14 '22 00:10

iainn