class - Variable variables in classes using PHP 7

460

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?

836

Answer

Solution:

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']}
17

Answer

Solution:

this is working on all version of php

<?php

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

People are also looking for solutions to the problem: macos - How can I install xdebug PHP extension in PHP 7.1.14, which is installed on osx high sierra?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.