Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 742
Marco Avatar asked Apr 21 '26 02:04

Marco


1 Answers

I'm afraid not, as you already found out yourself PHP7 interprets this expression differently from PHP5. The manual explicitly states

Code that used the old right-to-left evaluation order must be rewritten to explicitly use that evaluation order with curly braces

So you'll have to replace all the

$foo->$bar['baz']

With

$foo->{$bar['baz']}
like image 94
Niels Avatar answered Apr 22 '26 20:04

Niels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!