class - Variable variables in classes using PHP 7
Actually I'm migrating a bigger project from PHP 5.3.3 to PHP 7.1.13. In older versions of PHP it was possible to code following access to variable variables:
class MyClass {};
$myVar = array("hello","world");
$myClass = new MyClass();
$myClass->$myVar[0] = "test 0"; // sets "test 0" to $myClass->hello
$myClass->$myVar[1] = "test 1"; // sets "test 1" to $myClass->world
print_r($myClass);
This shows:
MyClass Object
(
[hello] => test 0
[world] => test 1
)
Using the same code in PHP 7 it shows:
MyClass Object
(
[Array] => Array
(
[0] => test 0
[1] => test 1
)
)
In PHP 7 I figured out, that I have to use this way to get the same result:
$myClass->{$myVar[0]} = "test 0";
$myClass->{$myVar[1]} = "test 1";
I found in the documentation that php5 and php7 interpretate this on different ways: http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling.indirect
Is there any chance to keep the old code or do I have to recode every appearance of this? Maybe some php.ini settings or something like this? Do you have any ideas?
Answer
Solution:
I'm afraid not, as you already found out yourself PHP7 interprets this expression differently from PHP5. The manual explicitly states
So you'll have to replace all the
With
Answer
Solution:
this is working on all version of php